Android intents, notification and broadcast recievers

Uploaded on


  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. Android Intents, Services, Notifications and Broadcast Recievers
  • 2. What’s our Intent ?
    Intent in Android
    Intents are used as a message-passing mechanism that works both within application, and between applications.
    Intents in Android are used to fulfill the intentions to –
    An Activity or Service be started to perform an action, usually with (or on) a particular piece of data
    Broadcast that an event (or action) has occurred
    Explicitly start a particular Service or Activity
    Types of Intents
    Explicit –Where the Activity or the Service class to be loaded is explicitly defined
    Implicit – Where an action be performed on a piece of data is requested
  • 3. Running an Intent Explicitly
    Switching from one Activity to another
    Without feedback
    Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
    With Feedback
    private static final int SHOW_SUBACTIVITY = 1;
    Intent intent = new Intent(this, MyOtherActivity.class);
    startActivityForResult(intent, SHOW_SUBACTIVITY);
  • 4. Implicitly Starting an Activity
    Implicit Intent is a mechanism that lets anonymous application components service action requests.
    Implicit Activity is started as a sub-Activity that’s inherently connected to its parent. A sub-Activity triggers an event handler within its parent Activity when it closes.
    Intentintent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:555-2368"));
    To nominate an action to perform and, optionally, supply the URI of the data to perform that action on.
    When our sub-Activity is ready to return, call setResult before finish to return a result to the calling Activity.
  • 5. Native Android Actions
  • 6. Sub-Activity Handler
    When a sub-Activity closes, the onActivityResult event handler is fired within the calling Activity.
    Override this method to handle the results returned by sub-Activities.
    This method takes 3 parameters-
    Request code The request code that was used to launch the returning sub-Activity.
    Result code The result code set by the sub-Activity to indicate its result. It can be any integer value, but typically will be either Activity.RESULT_OK or Activity.RESULT_CANCELED.
    Intent– The Intent used to return the packaged data
  • 7. Intent Filters
    Intent Filters are used to register Activities, Services, and Broadcast Receivers as being capable of performing an action on a particular kind of data.
    Using Intent Filters, application components announce that they can respond to action requests from any application installed on the device.
    1. Android puts together a list of all the Intent Filters available from the installed packages.
    2. Intent Filters that do not match the action or category associated with the Intent being resolved are removed from the list.
    2.1. Action matches are made
    2.2. Category matching is stricter
    3. Finally, each part of the Intent’s data URI is compared to the Intent Filterdsata tag. 3.1. The MIME type is the data type of the data being matched
    3.2. The scheme is the ‘‘protocol’’ part
    3.3 For a hostname to match, the Intent Filter’s scheme must also pass.
  • 8. 8
    Android Notifications
    Notification message is shown on the top of the screen, to alert users that events have occurred that may require attention.
    TheNotificationManagerclass is responsible for handling the Notifications- Its capability are
    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)
  • 9. 9
    Creating a Notification
    Pending Intent
    By giving a PendingIntent to another application, we are granting it the right to perform the operation we have specified as if the other application was ourself (with the same permissions and identity).
    This is used in setting the notification
    Intent intent = new Intent(this, MyActivity.class);
    PendingIntentlaunchIntent = PendingIntent.getActivity(context, 0, intent, 0);
  • 10. Android Service
    A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
    Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC).
  • 11. A service can essentially take two forms:
    Started –
    • A service is "started" when an application component (such as an activity) starts it by calling startService().
    • 12. Once started, a service can run in the background indefinitely.
    • 13. When the operation is done, the service should stop itself.
    • A service is "bound" when an application component binds to it by calling bindService().
    • 14. A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC).
  • 15. Importance of Services and their use
    A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application).
    This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
    A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.
  • 16. Creating a Service and associating it with an Activity
    Create a class that extends the Service class
    Add this new Service to the manifest by adding a new service tag within the application node.
    Override the onStartCommandand onCreate. Set the return type of the onStartCommandMethod from one of these to set the service behavior
    To start a Service, call startService; we can either use an action to implicitly start a Service with the appropriate Intent Receiver registered, or we can explicitly specify the Service using its class. If the Service requires permissions that our application does not have, the call to startService will throw a SecurityException.
    To stop a Service use stopService, passing an Intent that defines the Service to stop.
  • 17. Service Life Cycle
    Mode 1 - Context.startService()
    If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client.
    The service will at this point continue running until Context.stopService() or stopSelf() is called.
    Mode 2 - Context.bindService()
    On calling Context.bindService() to obtain a persistent connection to a service creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand().
    The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's Ibinder
  • 18. 15
    Android Interface Definition Language : AIDL
    It allows we to define the programming interface that both the client and service agree upon in order to communicate with each other using interprocess communication (IPC).
    When you build each application that contains the .aidl file, the Android SDK tools generate an IBinder interface based on the .aidl file and save it in the project's gen/ directory. The service must implement the IBinder interface as appropriate.
    To create a bounded service using AIDL, follow these steps:
    Create the .aidl file This file defines the programming interface with method signatures.
    Implement the interface The Android SDK tools generate an interface in the Java programming language, based on our .aidl file. This interface has an inner abstract class named Stub that extends Binder and implements methods from our AIDL interface. we must extend the Stub class and implement the methods.
    Expose the interface to clients Implement a Service and override onBind() to return our implementation of the Stub class.
  • 19. Broadcast Receivers
    A broadcast receiver is a class which extends BroadcastReceiverclass and which is registered as a receiver in an Android Application via the AndroidManifest.xml (or via code). This class will be able to receive intents via the sendBroadcast() method.
    Broadcast receiver is a component that responds to system-wide broadcast announcements
  • 20. There are two major classes of broadcasts that can be received:
    Normal broadcasts(sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time. This is more efficient.
    Ordered broadcasts(sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers
  • 21. Importance of Broadcast receivers
    Broadcast receivers are implemented In order to monitor and respond any changes in the intents which are registered with it.
    We ca attach a Broadcast Receiver with any activity or intent, in which if ay event or state change occurs, we have to perform some action or function corresponding to it.
    Broadcast receiver responds to system wide announcements, so we can register ay event In the system for monitoring and broadcasting ay change In the desired parameter
  • 22. 19
    SQLite Databases
    Android provides full support for SQLite databases. Any databases we create will be accessible by name to any class in the application, but not outside the application.
    To create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which we can execute a SQLite command to create tables in the database.
    getWritableDatabase() and getReadableDatabase()
    To write and read from database, their return type is SQLiteDatabase class that provides methods for database operations.
    SQLiteDatabase query() methods – to execute queries, these methods takes various parameters, for various quires.
    CursorIt’s the return type of any SQLite query and the mechanism with which we can navigate results from a database query and read rows and columns.
  • 23. 20
    Steps to create and read from a database
    private void createDatabase() {
    myDatabase = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
    Cursor query(SQLiteDatabase db, String[] projectionIn, String selection, String[] selectionArgs, String groupBy, String having, String sortOrder, String limit)
    Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);
    float totalHoard = 0f;
    if (myGold.moveToFirst()) {
    do {
    float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);
    totalHoard += hoard;
    } while(myGold.moveToNext());
  • 24. 21
    Content Providers
    Content Providers - Content providers are interfaces to store and retrieve data and make it accessible to all applications. They're the only way to share data across applications
    How to use content-providers
    public class MyProvider extends ContentProvider {
    public boolean onCreate() {
    // TODO Construct the underlying database.
    return true;
  • 25. 22
    Using a Content-provider
    We should expose a public static CONTENT_URI property that returns the full URI of this provider
    We will use the URI matcher for this
    public static final Uri CONTENT_URI = Uri.parse(myURI);
    static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI("com.paad.provider.myApp", "items", ALLROWS);
    uriMatcher.addURI("com.paad.provider.myApp", "items/#", SINGLE_ROW);
    Then expose queries and transactions on our Content Provider by implementing the delete, insert,update, and query methods.
    Register our provider by -
    <provider android:name="MyProvider"
  • 26. 23
    Using Content-Resolver
    The Content resolver is the interface that is used to obtain the underlying data using its various abstract methods.
    ContentResolvercr = 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);
  • 27. 24
  • 28. 25