Saturday, August 30, 2014

Native Android Content Providers

Android exposes several native databases using Content Providers
Android.provider package includes classes that can simplify access to many of the most useful providers

Browser
Browser Content Provider to read or modify bookmarks, browser history, or web searches

CallLog
View or update the call history, including both incoming and outgoing calls, together with missed calls and call details like caller ID and call durations

ContactsContract
to retrieve, modify, or store your contacts’ details

MediaStore
centralized, managed access to the multimedia on your device, including audio, video, and images

Settings
access the device’s preferences using the Settings provider

UserDictionary
Access (or add to) the user defined words added to the dictionary for use in IME predictive text input


Using the Media Store Provider

The MediaStore class includes Audio, Video, and Images subclasses, which in turn contain subclasses that are used to provide the column names and content URIs for each media provider

The Media Store segregates media kept on the internal and external volumes of the host device

MediaStore.<mediatype>.Media.EXTERNAL_CONTENT_URI
MediaStore.<mediatype>.Media.INTERNAL_CONTENT_URI

// Get a cursor over every piece of audio on the external volume.
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                                           null, null, null, null); 

// Let the activity manage the cursor lifecycle.
startManagingCursor(cursor);

// Use the convenience properties to get the index of the columns
int albumIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM); 
int titleIdx = cursor. getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);

String[] result = new String[cursor.getCount()];
if (cursor.moveToFirst())
  do { 
    // Extract the song title.
    String title = cursor.getString(titleIdx);
    // Extract the album name.
    String album = cursor.getString(albumIdx);

    result[cursor.getPosition()] = title + " (" + album + ")";
  } while(cursor.moveToNext());

Using the Contacts Provider

Android exposes  all the information available from the contacts database to any application granted the READ_CONTACTS permission

Introducing the Contacts Contract Content Provider

Reading Contact Details

Modifying and Augmenting Contact Details


Friday, August 29, 2014

Content Provider

Database is accessible to only the package that created it.

Android's way of sharing data across packages is through the use of content providers.

A content provider behaves very much like a database - you can query it, edit its contents, as well as add or delete content.

The data can be stored in a database, in files, or even over a network.

Android ships with many useful content providers

Browser : Stores data such as browser bookmarks, browser history, and so on
CallLog : Stores data such as missed calls, call details, and so on
Contacts : Stores contact details
MediaStore : Stores media fi les such as audio, video, and images
Settings : Stores the device’s settings and preferences

Querying a content provider

To query a content provider, you specify the query string in the form of a URI, with an optional
specifier for a particular row.

<standard_prefix>://<authority>/<data_path>/<id>

standard_prefix
The standard prefix for content providers is always content://

authority
The authority specifies the name of the content provider
Eg:
     contacts: Built-in contacts provider
     <fully qualified name>: for third party content providers

data_path
The data path specifies the kind of data requested
Eg.
    people: content://contacts/people

id
The id specifies the specific record requested
Eg.
content://contacts/people/2

Example Query Strings:

content://media/internal/images
content://media/external/images
content://call_log/calls
content://browser/bookmarks

Predefined Query String Constants

you can use a list of predefi ned query string constants in Android to specify the URI for the different data types.

Uri allContacts = Uri.parse(“content://contacts/people”);

Uri allContacts = ContactsContract.Contacts.CONTENT_URI;

Some examples of predefi ned query string constants

Browser.BOOKMARKS_URI
Browser.SEARCHES_URI
CallLog.CONTENT_URI
MediaStore.Images.Media.INTERNAL_CONTENT_URI
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
Settings.CONTENT_URI

To access the phone number of a contact, you need to query against the URI stored in ContactsContract.CommonDataKinds.Phone.CONTENT_URI

https://github.com/coderetriever/Android/tree/master/Provider

Projections

Specify the exact columns to return by creating an array containing the names of the column to return

Cursor c = managedQuery(allContacts, projection, null, null, null);

CursorLoader cursorLoader = new CursorLoader(this, allContacts, projection, null, null, null);
Cursor c = cursorLoader.loadInBackground();

String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};

Filtering 

SQL WHERE clause to filter the result of the query

third and fourth parameters
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ‘%Lee’”, null, null);

Cursor c;
if (android.os.Build.VERSION.SDK_INT <11) {
//---before Honeycomb---
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”}, null);

fourth and fifth parameters
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ‘%Lee’”,
null ,
null);
c = cursorLoader.loadInBackground();

CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”},
null);
c = cursorLoader.loadInBackground();

Sorting

SQL ORDER BY clause to sort the result of the query

last parameter of managedQuery
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”},
ContactsContract.Contacts.DISPLAY_NAME + “ ASC”);

Creating a custom content provider

To create a new Content Provider, extend the abstract ContentProvider class.

Override the onCreate method to create (and initialize) the underlying data source you’re planning to publish with this provider

import android.content.*;
import android.database.Cursor;
import android.net.Uri;
import android.database.SQLException;

public class MyProvider extends ContentProvider {

  @Override
  public boolean onCreate() {
    // TODO Construct the underlying database.
    return true;
  }
}

Expose a public static CONTENT_URI property that returns the full URI of this provider

content://com.<CompanyName>.provider.<ApplicationName>/<DataPath>

Content URIs can represent either of two forms:

Request for all values of that type (in this case all elements)
content://com.paad.provider.myapp/elements

Request for a single record
content://com.paad.provider.myapp/elements/5

It’s good practice to support access to your provider for both of these forms. The simplest way to do this is to use a UriMatcher

Using the UriMatcher to handle single or multiple query requests

public class MyProvider extends ContentProvider {

  private static final String myURI = "content://com.paad.provider.myapp/items";
  public static final Uri CONTENT_URI = Uri.parse(myURI);

  @Override
  public boolean onCreate() {
    // TODO: Construct the underlying database.
    return true;
  }

  // Create the constants used to differentiate between the different URI 
  // requests.
  private static final int ALLROWS = 1;
  private static final int SINGLE_ROW = 2;
  
  private static final UriMatcher uriMatcher;

  // Populate the UriMatcher object, where a URI ending in 'items' will correspond to a request for all items, and 'items/[rowID]' represents a single row.
  static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI("com.paad.provider.myApp", "items", ALLROWS);
    uriMatcher.addURI("com.paad.provider.myApp", "items/#", SINGLE_ROW);
  }
}

You can use the same technique to expose alternative URIs for different subsets of data

Exposing Access to the Data Source

Expose queries and transactions on your Content Provider by implementing the delete, insert, update, and query methods
These methods are the interface used by the Content Resolver to access the underlying data

Defining the MIME type that identifies the data the provider returns.
Override the getType method to return a String that uniquely describes your data type
Single item vnd.<companyname>.cursor.item/<contenttype>
All items vnd.<companyName>.cursor.dir/<contenttype>

@Override
public Cursor query(Uri uri, 
                    String[] projection, 
                    String selection, 
                    String[] selectionArgs, 
                    String sort) {
      
  // If this is a row query, limit the result set to the passed in row.        
  switch (uriMatcher.match(uri)) {
    case SINGLE_ROW : 
      // TODO: Modify selection based on row id, where:
      // rowNumber = uri.getPathSegments().get(1));
  }
  return null;
}

@Override
public Uri insert(Uri _uri, ContentValues _initialValues) {
  long rowID = [ ... Add a new item ... ]
        
  // Return a URI to the newly added item.
  if (rowID > 0) {
    return ContentUris.withAppendedId(CONTENT_URI, rowID);
  }
  throw new SQLException("Failed to add new item into " + _uri);
}

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
  switch (uriMatcher.match(uri)) {
    case ALLROWS: 
    case SINGLE_ROW:
    default: throw new IllegalArgumentException("Unsupported URI:" + uri);
  }
}

@Override
public int update(Uri uri, ContentValues values, String where, String[] 
whereArgs) {
  switch (uriMatcher.match(uri)) {
    case ALLROWS: 
    case SINGLE_ROW:
    default: throw new IllegalArgumentException("Unsupported URI:" + uri);
  }
}

@Override
public String getType(Uri _uri) {
  switch (uriMatcher.match(_uri)) {
    case ALLROWS: return "vnd.paad.cursor.dir/myprovidercontent";
    case SINGLE_ROW: return "vnd.paad.cursor.item/myprovidercontent";
    default: throw new IllegalArgumentException("Unsupported URI: " + _uri);
  }
}

Registering Your Provider

Once you have completed your Content Provider, it must be added to the application manifest.

Use the authorities tag to specify its base URI,

<provider android:name="MyProvider" android:authorities="com.paad.provider.myapp"/>

USING CONTENT PROVIDERS

Each application Context includes a ContentResolver instance

ContentResolver cr = getContentResolver();

Querying for Content

Using the query method on the ContentResolver object, pass in:

The URI of the Content Provider data you want to query
A projection that lists the columns you want to include in the result set\
A where clause that defines the rows to be returned. an include ? wildcards that will be
replaced by the values passed into the selection argument parameter
An array of selection argument strings that will replace the ?s in the where clause
A string that describes the order of the returned rows

ContentResolver cr = getContentResolver();

// Return all rows
Cursor allRows = cr.query(MyProvider.CONTENT_URI, null, null, null, null);

// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor someRows = cr.query(MyProvider.CONTENT_URI, 
                           null, where, null, order);

Adding, Updating, and Deleting Content

To perform transactions on Content Providers, use the delete, update, and insert methods on the ContentResolver object.

Inserts

// Get the Content Resolver
ContentResolver cr = getContentResolver();

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();

// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]

Uri myRowUri = cr.insert(MyProvider.CONTENT_URI, newValues);

// Create a new row of values to insert.
ContentValues[] valueArray = new ContentValues[5];

// TODO: Create an array of new rows
int count = cr.bulkInsert(MyProvider.CONTENT_URI, valueArray);

Deletes

ContentResolver cr = getContentResolver();

// Remove a specific row.
cr.delete(myRowUri, null, null);
// Remove the first five rows.
String where = "_id < 5";
cr.delete(MyProvider.CONTENT_URI, where, null);

Updates

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();

// Create a replacement map, specifying which columns you want to
// update, and what values to assign to each of them.
newValues.put(COLUMN_NAME, newValue);

// Apply to the first 5 rows.
String where = "_id < 5";

getContentResolver().update(MyProvider.CONTENT_URI, newValues, where, null);

Accessing Files in Content Providers

Content Providers represent files as fully qualified URIs rather than as raw file blobs

// Insert a new row into your provider, returning its unique URI.
Uri uri = getContentResolver().insert(MyProvider.CONTENT_URI, newValues);

try {
  // Open an output stream using the new row's URI.
  OutputStream outStream = getContentResolver().openOutputStream(uri);
  // Compress your bitmap and save it into your provider.
  sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
}
catch (FileNotFoundException e) { }


SQLite

Android databases are stored in the /data/data/<package_name>/databases folder on your device

By default all databases are private, accessible only by the application that created them

SQLite is a well regarded relational database management system (RDBMS).

SQLite differs from many conventional database engines by loosely typing each column, meaning that column values are not required to conform to a single type

https://github.com/coderetriever/Android/tree/master/Databases

Introducing the SQLiteOpenHelper

SQLiteOpenHelper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases

The onCreate() method creates a new database if the required database is not present.

The onUpgrade() method is called when the database needs to be upgraded.

  private static class myDbHelper extends SQLiteOpenHelper {
    public myDbHelper(Context context, String name, 
                      CursorFactory factory, int version) {
      super(context, name, factory, version);
    }

    // Called when no database exists in disk and the helper class needs to create a new one. 
    @Override
    public void onCreate(SQLiteDatabase _db) {
      _db.execSQL(DATABASE_CREATE);
    }

    // Called when there is a database version mismatch meaning that the version of the database on disk needs to be upgraded to the current version.
    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
      // Log the version upgrade.
      Log.w("TaskDBAdapter", "Upgrading from version " + 
                             _oldVersion + " to " +
                             _newVersion + ", which will destroy all old data");
        
      // Upgrade the existing database to conform to the new version. Multiple previous versions can be handled by comparing _oldVersion and _newVersion values.

      // The simplest case is to drop the old table and create a new one.
      _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
      // Create a new one.
      onCreate(_db);
    }
  }
}

dbHelper = new myDbHelper(context, DATABASE_NAME, null, DATABASE_VERSION);

SQLiteDatabase db;
try {
  db = dbHelper.getWritableDatabase();
}
catch (SQLiteException ex){
  db = dbHelper.getReadableDatabase();

} 

Opening and Creating Databases without SQLiteHelper

Setting up a database is a two-step process
  • First call openOrCreateDatabase to create the new database
  • Then call execSQL on the resulting database instance to run the SQL commands that will create your tables and their relationships

        private static final String DATABASE_NAME = "myDatabase.db";
private static final String DATABASE_TABLE = "mainTable";

private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " ( _id integer primary key autoincrement,"
+ "column_one text not null);";

SQLiteDatabase myDatabase;

private void createDatabase() {
myDatabase = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE,
null);
myDatabase.execSQL(DATABASE_CREATE);
}

Querying a Database

Each database query is returned as a Cursor. Think of the Cursor as a pointer to the result set from a database query

To execute a query on a database use the query method
  • should contain only unique values?
  • The name of the table to query
  • lists the columns to include in the result set
  • A ‘‘where’’ clause that defines the rows to be returned. can include ? wildcards that will be replaced by the values passed in through the selection argument parameter
  • An array of selection argument strings that will replace the ?’s in the where clause
  • A ‘‘group by’’ clause that defines how the resulting rows will be grouped
  • A ‘‘having’’ filter that defines which row groups to include if you specified a group by clause
  • A string that describes the order of the returned rows
  • An optional string that defines a limit for the number of returned rows

// Return all rows for columns one and three, no duplicates
String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3};
Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns,
null, null, null, null, null, null);
// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where,
null, null, null, order)

Extracting Results from a Cursor

Cursors are pointers to the result set within the underlying data. Cursor class includes a number of navigation functions.

moveToFirst
moveToNext
moveToPrevious
getCount
getColumnIndexOrThrow
getColumnName
getColumnNames
moveToPosition
getPosition

The startManagingCursor method integrates the Cursor’s lifetime into the calling Activity’s. When you’ve finished with the Cursor, call stopManagingCursor to do just that.

First use the moveTo<location> methods to position the cursor at the correct row of the result Cursor
Then use the type safe get<type> methods (passing in a column index) to return the value

String columnValue = myResult.getString(columnIndex);

int GOLD_HOARDED_COLUMN = 2;
Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);
float totalHoard = 0f;
// Make sure there is at least one row.
if (myGold.moveToFirst()) {
// Iterate over each cursor.
do {
float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);
totalHoard += hoard;
} while(myGold.moveToNext());
}
float averageHoard = totalHoard / myGold.getCount();

Content Values

ContentValues are used to insert new rows into tables.

Its put() method enables you to insert keys with values of different data types.

Adding, Updating, and Removing Rows

The SQLiteDatabase class exposes insert, delete, and update methods that encapsulate the SQL statements required to perform these actions

The execSQL method lets you execute any valid SQL on your database tables

Any time you modify the underlying database values, you should call refreshQuery on each Cursor that has a view on the affected table

Inserting New Rows

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
// Insert the row into your table
myDatabase.insert(DATABASE_TABLE, null, newValues);

Updating a Row

Call update on the database, passing in the table name, the updated Content Values object, and a where clause that specifies the row(s) to update

// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
String where = KEY_ID + "=" + rowId;
// Update the row with the specified index with the new values.
myDatabase.update(DATABASE_TABLE, newValues, where, null);

Deleting Rows

specifying the table name and a where clause

myDatabase.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null);

Upgrading the Database

Sometimes, after creating and using the database, you may need to add additional tables, change
the schema of the database, or add columns to your tables. In this case, you need to migrate your
existing data from the old database to a newer one

To upgrade the database, change the DATABASE_VERSION constant to a value higher than the
previous one.

static final int DATABASE_VERSION = 2;

Pre-Creating the Database

In real-life applications, sometimes it would be more effi cient to pre-create the database at design
time rather than runtime.

To pre-create a SQLite database, you can use SQLite Database Browser

With the database created at design time, the next thing you should do is bundle it together with
your application so that you can use it in your application

NOTE Note that a filename for files added to the assets folder must be in
lowercase letters. As such, a filename such as MyDB is invalid, whereas mydb is fine.

When the activity is created, you copy the database fi le located in the assets folder into the /data/
data/net.learn2develop.Databases/databases/ folder on the Android device

You copy the database fi le only if it does not exist in the destination folder

Wednesday, August 27, 2014

SMS

Android uses a permissions-based policy whereby all the permissions needed by an application must be specified in the AndroidManifest.xml file

To send an SMS message programmatically, you use the SmsManager class.
Call the getDefault() static method to obtain an SmsManager object
send the SMS message using the sendTextMessage() method

private void sendSMS(String phoneNumber, String message)
{
     SmsManager sms = SmsManager.getDefault();
     sms.sendTextMessage(phoneNumber, null, message, null, null);
}

➤ destinationAddress — Phone number of the recipient
➤ scAddress — Service center address; use null for default SMSC
➤ text — Content of the SMS message
➤ sentIntent — Pending intent to invoke when the message is sent (discussed in more detail in the
next section)
➤ deliveryIntent — Pending intent to invoke when the message has been delivered (discussed in
more detail in the next section)

NOTE If you send an SMS message programmatically using the SmsManager class, the message sent will not appear in the built-in Messaging application of the sender.


Telephony

Launching the Dialer to Initiate Phone Calls

Use an Intent action to
  • start a dialer activity (ACTION)
  • specify the number to dial using the tel: schema as the data component (DATA)

Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:1234567"));
startActivity(intent);


Replacing the Native Dialer

Intercepting Intents that are currently serviced by the native dialer
Initiating, and optionally managing, outgoing calls.

<intent-filter> tags on your new Activity should listen for

Intent.ACTION_CALL_BUTTON
  • This action is broadcast when the device’s hardware call button is pressed
Intent.ACTION_DIAL
  • this Intent is used by applications which want to launch the dialer to make a phone call
Intent.ACTION_VIEW
  • The view action is used by applications wanting to view a piece of data
<activity
   android:name=".MyDialerActivity"
   android:label="@string/app_name">
   <intent-filter>
       <action android:name="android.intent.action.CALL_BUTTON" />
       <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
   <intent-filter>
       <action android:name="android.intent.action.VIEW" />
       <action android:name="android.intent.action.DIAL" />
       <category android:name="android.intent.category.DEFAULT" />
       <category android:name="android.intent.category.BROWSABLE" />
       <data android:scheme="tel" />
    </intent-filter>
</activity>


Accessing Phone and Network Properties and Status

Access to the telephony APIs is managed by the Telephony Manager, accessible using the getSystemService method

String srvcName = Context.TELEPHONY_SERVICE;
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName);



Reading Phone Device Details

Monitoring Changes in Phone State Using the Phone State Listener

To monitor and manage phone state

<uses-permission android:name="android.permission.READ_PHONE_STATE" />


Monitoring Incoming Phone Calls

PhoneStateListener callStateListener = new PhoneStateListener() {
      public void onCallStateChanged(int state, String incomingNumber) {
             // TODO React to incoming call.
      }
};


telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

state parameter represents the current call state
  • TelephonyManager.CALL_STATE_IDLE
    • When the phone is neither ringing nor in a call
  • TelephonyManager.CALL_STATE_RINGING
    • When the phone is ringing
  • TelephonyManager.CALL_STATE_OFFHOOK
    • When the phone is currently in a call
Using Intent Receivers to Monitor Incoming Phone Calls


Telephony Manager will broadcast an ACTION_PHONE_STATE_CHANGED Intent when phone state changes as a result of

  • incoming call
  • accepted call
  • terminated call

Intent also includes up to two extras:

intent.getStringExtra(TelephonyManager.EXTRA_STATE)
intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)

Can listen for incoming phone calls at any time, even if the application is not running.

It needs, 
   
<uses-permission android:name="android.permission.READ_PHONE_STATE" />







Tuesday, August 26, 2014

Alarms

Notifications

For messages that are important, you should use a more persistent method by using the NotificationManager.

NotificationManager displays a persistent message at the top of the device, commonly known as the status bar/notification bar.

Notifications are handled by the Notification Manager, and currently have the ability to
  • Create new status bar icons
  • Display additional information (and launch an Intent) in the extended status bar window
  • Flash the lights/LEDs
  • Vibrate the phone
  • Sound audible alerts (ringtones, Media Store audio)

Introducing the Notification Manager

The Notification Manager is a system Service used to handle Notifications

String svcName = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager;
notificationManager = (NotificationManager)getSystemService(svcName);

NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

Using the Notification Manager you can
  • trigger new Notifications
  • modify existing ones
  • remove those that are no longer required

Creating Notifications

Android offers a number of ways to convey information to users using Notifications.
1. The status bar icon
2. The extended notification status drawer
3. Additional phone effects such as sound and vibration

Creating a Notification and Configuring the Status Bar Icon

// Choose a drawable to display as the status bar icon
int icon = R.drawable.icon;
// Text to display in the status bar when the notification is launched
String tickerText = "Notification";
// The extended status bar orders notification in time order
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);

Set the Notification object’s number property to display the number of events a status bar icon represents

Setting this value to a number greater than 1, overlays the values as a small number over the status bar icon

notification.number++;

Configuring the Extended Status Notification Display

can configure the appearance of the Notification within the extended status window in two ways:
1. Use the setLatestEventInfo method to update the details displayed in the standard extended
status Notification display.
2. Set the contentView and contentIntent properties to assign a custom UI for the extended
status display using a Remote View.

Triggering a notification

To fire a Notification, pass it in to the notify method on the NotificationManager along with an integer reference ID

int notificationID = 1;
notificationManager.notify(notificationID, notification);

To update a Notification that’s already been fired, re-trigger it using the Notification Manager, passing the notify method the same reference ID

Canceling a notification

Canceling a Notification removes its status bar icon and clears it from the extended status window

You also use the reference ID to cancel Notifications by calling the cancel method on the Notification
Manager

notificationManager.cancel(notificationID);

Example


public class MyActivity extends Activity
{
    public void onClick(View view) {
        displayNotification();
    }
    
    protected void displayNotification()
    {
        //---PendingIntent to launch activity if the user selects this notification---
        Intent i = new Intent(this, NotificationView.class);
        i.putExtra("notificationID", notificationID);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

//The message shown in the status bar is provided to the constructor         Notification notif = new Notification(R.drawable.ic_launcher, "Reminder: Meeting starts in 5 minutes", System.currentTimeMillis());

        CharSequence from = "System Alarm";
        CharSequence message = "Meeting with customer at 3pm...";
        
//Set the details of the notification using setLatestEventInfo method on the Notification instance. The details would show up when the status bar is swiped down. Also pass a pending intent that has to be invoked when the notification is tapped
        notif.setLatestEventInfo(this, from, message, pendingIntent);

        //---100ms delay, vibrate for 250ms, pause for 100 ms and
        // then vibrate for 500ms---
        notif.vibrate = new long[] { 100, 250, 100, 500};
        nm.notify(notificationID, notif);        
    }
}

public class OnNotificationClickActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification);
            
        //---look up the notification manager service---
        NotificationManager nm = (NotificationManager) 
            getSystemService(NOTIFICATION_SERVICE);
        
        //Get the notificationID of the notification to cancel
        int notificationID = getIntent().getExtras().getInt("notificationID")
                 
        //---cancel the notification that we started--- 
        nm.cancel(notificationID);
    }
}

Toasts

Toasts are transient Dialog boxes that remain visible for only a few seconds before fading out

Context context = getApplicationContext();
String msg = "To health and happiness!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, msg, duration);
toast.show();

Customizing Toasts

can modify a Toast by setting its display position and assigning it alternative Views or layouts

Context context = getApplicationContext();
String msg = "To the bride and groom!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, msg, duration);
int offsetX = 0;
int offsetY = 0;
toast.setGravity(Gravity.BOTTOM, offsetX, offsetY);
toast.show();


Threading

All Android application components — including
Activities
Services
Broadcast Receivers
— start on the main application thread

Android offers two alternatives for backgrounding your processing.
  • AsyncTask
  • custom implementation of Threads
Using AsyncTask to Run Asynchronous Tasks

Offers the convenience of event handlers synchronized with the GUI thread to let you update Views and other UI elements to report progress or publish results when your task is complete



Creating a new Asynchronous Task

AsyncTask<[Input Parameter Type], [Progress Report Type], [Result Type]>

private class MyAsyncTask extends AsyncTask<String, Integer, Integer> {
  @Override
  protected void onProgressUpdate(Integer... progress) {
    // [... Update progress bar, Notification, or other UI element ...]
  }

  @Override
  protected void onPostExecute(Integer... result) {
    // [... Report results via UI update, Dialog, or notification ...]
  }

  @Override
  protected Integer doInBackground(String... parameter) {
    int myProgress = 0;
    // [... Perform background processing task, update myProgress ...]
    PublishProgress(myProgress)
    // [... Continue performing background processing task ...]

    // Return the value to be passed to onPostExecute
    return result;
  }
}

doInBackground
  • This method will be executed on the background thread
  • Use the publishProgress method to allow onProgressUpdate to post progress updates to the UI
  • When your background task is complete, return the final result for the onPostExecute handler to report it to the UI.
onProgressUpdate
  • Override this handler to post interim updates to the UI thread.
  • This handler is synchronized with the GUI thread when executed, so you can safely modify UI elements.
onPostExecute
  • When doInBackground has completed, the return value from that method is passed in to this event handler.
  • Use this handler to update the UI once your asynchronous task has completed
Running an Asynchronous Task

new MyAsyncTask().execute("inputString1", "inputString2");



Manual Thread Creation and GUI Thread Synchronization

Creating a new Thread

// This method is called on the main GUI thread.
private void mainProcessing() {
  // This moves the time consuming operation to a child thread.
  Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background");
  thread.start();
}

// Runnable that executes the background processing method.
private Runnable doBackgroundThreadProcessing = new Runnable() {
  public void run() {
    backgroundThreadProcessing();
  }
};

// Method which does some processing in the background.
private void backgroundThreadProcessing() {
  [ ... Time consuming operations ... ]
}

If you are running within an Activity, you can also use the runOnUiThread method, which lets you force a method to execute on the same thread as the Activity UI.

Synchronizing with the Activity’s GUI thread

runOnUiThread(new Runnable() {
    public void run() {
        // TODO Update a View.
    }
});

In other circumstances (such as Toasts and Notifications) you can use the Handler class to post methods onto the thread in which the Handler was created

// *******************************************************************
// ** Using a Handler to synchronize with the GUI thread
// Initialize a handler on the main thread.
private Handler handler = new Handler();

private void mainProcessing() {
  Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background"); 
  thread.start();
}

private Runnable doBackgroundThreadProcessing = new Runnable() {
  public void run() {
    backgroundThreadProcessing();
  }
};

// Method which does some processing in the background.
private void backgroundThreadProcessing() {
  [ ... Time consuming operations ... ]
  handler.post(doUpdateGUI); 
}

// Runnable that executes the update GUI method.
private Runnable doUpdateGUI = new Runnable() {
  public void run() {
    updateGUI();
  }
};

private void updateGUI() {
  [ ... Open a dialog or modify a GUI element ... ]
}

Examples

Hangs UI

public void startCounter(View view) {
    for (int i=0; i<=1000; i++) {
          txtView1.setText(String.valueOf(i));
          try {
                   Thread.sleep(1000);
                } catch (InterruptedException e) {}
          }
    }

This ties up the UI, which is waiting for the display of the numbers to be completed.

A Thread trying to access a View on the UI

  public void startCounter(View view) {  
    Log.d("Threading", "running");
    new Thread(new Runnable() {
@Override
public void run() {
    for (int i=0; i<=1000; i++) {
    Log.d("Threading", "running");
    txtView1.setText(String.valueOf(i));
    try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d("Threading", e.getLocalizedMessage());
}
    }    
}    
    }).start();

This code that is placed inside the Runnable block is on a separate thread, which tries to update the UI, which is not a safe thing to do because Android UIs are not thread-safe.

Using Post method on a View inside a Thread

To resolve this, you need to use the post() method of a View to create another Runnable block to be added to the message queue. 

The new Runnable block created will be executed in the UI thread

    public void startCounter(View view) 
    {  
    //Do not hangup the UI
    new Thread(new Runnable() {
    @Override
    public void run()
    {
    for(int i = 0; i <= 1000; i++)
    {
    final int valueOfI = i;
   
    //Place the job of updating the UI in the message queue
    txtView1.post(new Runnable() {
    public void run()
    {
    txtView1.setText(String.valueOf(valueOfI));
    }
    });
   
    try
    {
    Thread.sleep(1000);
    }catch(InterruptedException e)
    {
    Log.d("Threading ", e.getLocalizedMessage());
    }
    }
    }
    }
    ).start();        
    }    
Using a Handler to update UI

static Handler UIupdater = new Handler() {
@Override
public void handleMessage(Message msg) {              
byte[] buffer = (byte[]) msg.obj;

//---convert the entire byte array to string---
String strReceived = new String(buffer);

//---display the text received on the TextView---              
txtView1.setText(strReceived);
Log.d("Threading", "running");
}
};
    
    public void startCounter(View view) {  
    new Thread(new Runnable() {
    @Override
    public void run() {    
    for (int i=0; i<=1000; i++) {    
    //---update the main activity UI using a UIupdater
                    ThreadingActivity.UIupdater.obtainMessage(
                        0,  String.valueOf(i).getBytes() ).sendToTarget();
   
    //---insert a delay    
    try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d("Threading", e.getLocalizedMessage());
}
    }
    }    
    }).start();
    }

https://github.com/coderetriever/Android/tree/master/ThreadingTwo

https://github.com/coderetriever/Android/tree/master/ThreadingThree

https://github.com/coderetriever/Android/tree/master/ThreadFour