A simple example of using AlarmManager to trigger a BroadcastReceiver to be called in 10 seconds later.
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.
This example also show how to determine calling set() or setExact() depends on Build.VERSION.SDK_INT. But no demo how in-exact with calling set(), because alarms scheduled in the near future will not be deferred as long as alarms scheduled far in the future.
AlarmReceiver.java
package com.example.androidalarm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,
"AlarmReceiver.onReceive()",
Toast.LENGTH_LONG).show();
}
}
This example show how to save bitmap to storage (SD Card) as file, and insert to MediaStore.
As a example, the bitmap is retrieved from ImageView by calling ((BitmapDrawable)imageView.getDrawable()).getBitmap(), note that it's not always work, depends on how to load image to ImageVIew.
To save file to external storage, permission of "android.permission.WRITE_EXTERNAL_STORAGE" is needed in AndroidManifest.xml. Otherwise you cannot save the file, but no error reported.
In this example:
- The first button save the bitmap as file, with specified path. In this case, MediaStore may not know there are new image, such that may be you cannot view it in Android Gallery App or Photos App.
- The second button insert the bitmap to MediaStore by calling MediaStore.Images.Media.insertImage(ContentResolver cr, Bitmap source, String title, String description), to MediaStore path. Such that you can view it in Android Gallery App or Photos App.
- The third button save the bitmap as file, then insert the file to MediaStore by calling MediaStore.Images.Media.insertImage(ContentResolver cr, String imagePath, String name, String description). In this case, you save two files actually.
package com.example.androidsavebitmap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.support.v7.app.ActionBarActivity;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/*
* "android.permission.WRITE_EXTERNAL_STORAGE" is needed
* otherwise, cannot save but no error report
*/
public class MainActivity extends ActionBarActivity {
ImageView imageView;
Button btnSaveExternalStorageDirectory;
Button btnSaveMediaStore;
Button btnSaveFileAndMediaStore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.image);
btnSaveExternalStorageDirectory = (Button)findViewById(R.id.saveExternalStorageDirectory);
btnSaveExternalStorageDirectory.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
/*
* Save bitmap to ExternalStorageDirectory
*/
//get bitmap from ImageVIew
//not always valid, depends on your drawable
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
//always save as
String fileName = "test.jpg";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File ExternalStorageDirectory = Environment.getExternalStorageDirectory();
File file = new File(ExternalStorageDirectory + File.separator + fileName);
FileOutputStream fileOutputStream = null;
try {
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes.toByteArray());
Toast.makeText(MainActivity.this,
file.getAbsolutePath(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}});
btnSaveMediaStore = (Button)findViewById(R.id.saveMediaStore);
btnSaveMediaStore.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
/*
* Save bitmap to MediaStore
*/
//get bitmap from ImageVIew
//not always valid, depends on your drawable
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
ContentResolver cr = getContentResolver();
String title = "myBitmap";
String description = "My bitmap created by Android-er";
String savedURL = MediaStore.Images.Media
.insertImage(cr, bitmap, title, description);
Toast.makeText(MainActivity.this,
savedURL,
Toast.LENGTH_LONG).show();
}});
btnSaveFileAndMediaStore = (Button)findViewById(R.id.saveExternalStorageDirectoryMediaStore);
btnSaveFileAndMediaStore.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
/*
* Save bitmap to ExternalStorageDirectory
*/
//get bitmap from ImageVIew
//not always valid, depends on your drawable
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
//always save as
String fileName = "test.jpg";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File ExternalStorageDirectory = Environment.getExternalStorageDirectory();
File file = new File(ExternalStorageDirectory + File.separator + fileName);
FileOutputStream fileOutputStream = null;
try {
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes.toByteArray());
ContentResolver cr = getContentResolver();
String imagePath = file.getAbsolutePath();
String name = file.getName();
String description = "My bitmap created by Android-er";
String savedURL = MediaStore.Images.Media
.insertImage(cr, imagePath, name, description);
Toast.makeText(MainActivity.this,
savedURL,
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}});
}
}
Google Handwriting Input allows you to handwrite text on your phone or tablet in 82 languages. It supports printed and cursive writing, with or without a stylus. Google Handwriting Input also supports hundreds of emojis, so you can express yourself in any Android app.
Key features:
• A useful complement to touchscreen typing or voice input
• A fun way to enter emojis by drawing
• Useful for languages that can be challenging to type on a standard keyboard
• Works across your Android phones and tablets running Android 4.0.3 and up
• If you claim your handwriting is terrible, try it out and see if it can convince you otherwise
On the Android to Arduino Uno direction, user tap on the custom view (8x8 squares) to turn ON/OFF LEDs on Arduino, or select character from the spiner.
On the Arduino Uno to Android direction, tap on the "Load from Arduino" button on Android, Android send a command to Arduino, then Arduino send back 64 bytes back to Android, represent (inverted) ON/OFF state of each dots.
The right hand side TextView show the data received on Android.
Roughly, to implement receiving on Android
- MainActivity implement Runnable
- override run() method to monitor UsbRequest
- start background thread after openDevice() to run the run() method
Connection:
Android - USB OTG Cable - USB Cable - Arduino Uno - 8x8 LED Matrix
This example we will open PopupWindow together with a AsyncTask. Once the AsyncTask count for 10 seconds, it will dismiss the PopupWindow; to show how to dismiss PopupWindow outside itself.
/res/layout/popup.xml, the layout of the PopupWindow.
Remark for AsyncTask:
- In this implementation, I haven't stop the AsyncTask if the PopupWindow dismissed by button. So the associated AsyncTask still run in background. I intentionally implement like this, to show the behavior of AsyncTask.
- Starting with HONEYCOMB, AsyncTask are executed on a single thread, that means one by one (read Run multi AsyncTask at the same time). If user start a PopupWindow A and AsyncTask A, and dismiss PopupWindow A with button, AsyncTask A still running. Then start PopupWindow B and AsyncTask B. It will wait AsyncTask A finished, then start AsyncTask B,...then finish, then dismiss PopupWindow B.
Practical and real-life examples showing how and where NFC can be used
Discover how to exploit NFC capabilities to enhance your apps to easily share and interact with the world
Learn how to extend cross-device content sharing by taking advantage of Android Beam's capabilities
In Detail
Near Field Communication, or simply NFC, is an emerging technology with endless applicability. Its low battery consumption and simplicity are the keys to its success.
Near Field Communication with Android Cookbook is a hands-on book that will help you to set up your development environment, get to know the basics of NFC, and then use what you learn to create more enhanced and practical applications. This practical guide will teach you all you need know about NFC to get you started in developing outstanding out-of-the-box applications.
What you will learn from this book
Work with the foreground dispatch system NFC data exchange format
Create several applications to consolidate knowledge and see what NFC can be used for
Read and write tags with URI, text, mime, and external types
Share content across two NFC-enabled devices
Extend NFC usage using Bluetooth and Wi-Fi
Combine NFC with social networks and games
Use Open NFC for Android to set up a virtual development and testing environment
Approach
An easy-to-follow guide, full of hands-on examples of and real-world applications. Each recipe is explained and placed in context.
Who this book is written for
If you want to learn how to create NFC-enabled Android applications, this is the book for you. Perhaps you already know a bit about Android application developments but have never used NFC, or perhaps you know a little about NFC android development but want some more advanced features and examples. In either case, this book will get you up and running quickly. You are expected to have Android programming knowledge.
Although wearable devices have existed since the 70s, they have only recently become mainstream. Google Glass and Android Wear smartwatches, in particular, are relatively new devices that provide countless opportunities for creating innovative apps with unprecedented user experiences. Beginning Android Wearables gives you the skills you need to take part in the wearable revolution and to delight your users by providing the information they need at the tips of their fingers.
This book is very practical and contains many examples that not only show you how to write code for Glass and Android Wear, but also demonstrate how to apply this code in the context of an app.
What you’ll learn
Build notifications for handheld apps that are automatically shared with Glass or Android Wear, and learn to customize these notifications specifically for wearables
Create apps that run directly on Android Wear devices and leverage the Android Wear SDK
Use the wearable UI library to build effective user interfaces for Android Wear
Use the wearable data layer API to share and synchronize data between a handheld device and Android Wear
Build custom watch faces for Android Wear
Build Glassware (that is, apps for Glass) using the Glass Development Kit (GDK)
Use the views and widgets of the GDK to build effective user interfaces for Glass
Receive user input on Glass with touchpad gestures, head gestures, and voice recognition
Take pictures and record videos on Glass by either leveraging the native camera app or with the Camera API
Utilize location providers and orientation sensors to build contextually sensitive apps
Who this book is for
This book only requires basic knowledge of Android programming. Prior to this book, you should have read or are at least comfortable with Android after using Apress tutorials, Android Apps for Absolute Beginners or Beginning Android
Table of Contents
Part I - Introduction
1. Introducing Android Wearables
Part II - Notifications
2. Reviewing Notifications for Android
3. Customizing Notifications for Wearables
Part III - Android Wear
4. Running Apps Directly on Android Wear
5. Android Wear UI Essentials
6. The Wearable Data Layer API
7. Creating Custom Watch Faces
Part IV - Google Glass
8. Running Apps Directly on Glass
9. Glass User Interface Essentials
10. Voice and Input
11. The Camera: Taking Pictures and Recording Video
Part V - Android Wear and Glass
12. Location and Orientation
Android programming example to set icon and background of ActionBar. (Assume your activity extends android.support.v7.app.ActionBarActivity, with android.support.v7.app.ActionBar)
It's a Android app example in SDK, to implement SoftKeyboard. It should be in in your Android SDK directory:
<Android SDK>/samples/android-22/legacy/SoftKeyboard
If you import in Android SDK-Eclipse, may be you have to manually set your target SDK:
Right click your project -> Properties -> Select Android on the left, and check Project Build Target of Android 5.1.
Otherwise, error of No resource identifier found for attribute 'supportsSwitchingToNextInputMethod' will be reported in method.xml.
Develop database-driven Android applications and stay ahead of the curve
Explore the best techniques to use cursors and loaders to achieve optimum results
A step-by-step approach to use SQLite for building Android applications
Who This Book Is For
This is an ideal book for Android programmers who want to explore SQLite databases based on Android applications. The general competency level expected of the reader is prior knowledge of developing applications and basic knowledge of Android and SQL.
In Detail
SQLite is an open source relational database management system. Android uses the SQLite database to store and retrieve data persistently. The driving force behind the platform is the database, enabling a myriad of choices for developers making cutting-edge applications.
Android SQLite Essentials focuses on the core concepts behind building database-driven applications. This book covers the basic and advanced topics with equivalent simplicity and detail, in order to enable readers to quickly grasp and implement the concepts to build an application database.
This book takes a hands-on, example-based approach to help readers understand the core topics of SQLite and Android database-driven applications. This book focuses on providing you with latent as well as widespread knowledge about practices and approaches towards development in an easily understandable manner.
- Add function of Run/Stop, and Repeat setting
- Instead of disable hardware acceleration in AndroidManifest.xml, the custom AnimatedGifView disable hardware acceleration by calling setLayerType(), for API Level 11.
Our custom view, AnimatedGifView.gif
package com.example.androidgif;
import java.io.InputStream;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.view.View;
public class AnimatedGifView extends View {
private InputStream gifInputStream;
private Movie gifMovie;
private int movieWidth, movieHeight;
private long movieDuration;
private long movieRunDuration;
private long lastTick;
private long nowTick;
private boolean repeat = true;
private boolean running = true;
public void setRepeat(boolean r) {
repeat = r;
}
public void setRunning(boolean r) {
running = r;
}
public AnimatedGifView(Context context) {
super(context);
init(context);
}
public AnimatedGifView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public AnimatedGifView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
// Turn OFF hardware acceleration
// API Level 11
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
setFocusable(true);
gifInputStream = context.getResources().openRawResource(
R.drawable.android_er);
gifMovie = Movie.decodeStream(gifInputStream);
movieWidth = gifMovie.width();
movieHeight = gifMovie.height();
movieDuration = gifMovie.duration();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(movieWidth, movieHeight);
}
public int getMovieWidth() {
return movieWidth;
}
public int getMovieHeight() {
return movieHeight;
}
public long getMovieDuration() {
return movieDuration;
}
@Override
protected void onDraw(Canvas canvas) {
if(gifMovie == null){
return;
}
nowTick = android.os.SystemClock.uptimeMillis();
if (lastTick == 0) { // first time
movieRunDuration = 0;
}else{
if(running){
movieRunDuration += nowTick-lastTick;
if(movieRunDuration > movieDuration){
if(repeat){
movieRunDuration = 0;
}else{
movieRunDuration = movieDuration;
}
}
}
}
gifMovie.setTime((int)movieRunDuration);
gifMovie.draw(canvas, 0, 0);
lastTick = nowTick;
invalidate();
}
}