Android intents, notification and broadcast recievers


Published on

  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Android intents, notification and broadcast recievers

  1. 1. Android Intents, Services, Notifications and Broadcast Recievers<br />1<br />
  2. 2. What’s our Intent ?<br />Intent in Android<br />Intents are used as a message-passing mechanism that works both within application, and between applications.<br />Intents in Android are used to fulfill the intentions to –<br />An Activity or Service be started to perform an action, usually with (or on) a particular piece of data<br /> Broadcast that an event (or action) has occurred<br /> Explicitly start a particular Service or Activity<br />Types of Intents<br />Explicit –Where the Activity or the Service class to be loaded is explicitly defined<br />Implicit – Where an action be performed on a piece of data is requested<br />2<br />
  3. 3. Running an Intent Explicitly<br />Switching from one Activity to another<br />Without feedback<br />Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);<br />startActivity(intent);<br />With Feedback<br />private static final int SHOW_SUBACTIVITY = 1;<br />Intent intent = new Intent(this, MyOtherActivity.class);<br />startActivityForResult(intent, SHOW_SUBACTIVITY);<br />3<br />
  4. 4. Implicitly Starting an Activity<br />Implicit Intent is a mechanism that lets anonymous application components service action requests.<br />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.<br />Intentintent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:555-2368"));<br />startActivity(intent);<br />To nominate an action to perform and, optionally, supply the URI of the data to perform that action on.<br />When our sub-Activity is ready to return, call setResult before finish to return a result to the calling Activity.<br />4<br />
  6. 6. Sub-Activity Handler<br />When a sub-Activity closes, the onActivityResult event handler is fired within the calling Activity.<br />Override this method to handle the results returned by sub-Activities.<br />This method takes 3 parameters-<br />Request code The request code that was used to launch the returning sub-Activity.<br />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.<br />Intent– The Intent used to return the packaged data<br />6<br />
  7. 7. Intent Filters<br />Intent Filters are used to register Activities, Services, and Broadcast Receivers as being capable of performing an action on a particular kind of data.<br />Using Intent Filters, application components announce that they can respond to action requests from any application installed on the device.<br />1. Android puts together a list of all the Intent Filters available from the installed packages.<br />2. Intent Filters that do not match the action or category associated with the Intent being resolved are removed from the list.<br />2.1. Action matches are made <br />2.2. Category matching is stricter<br />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<br />3.2. The scheme is the ‘‘protocol’’ part<br />3.3 For a hostname to match, the Intent Filter’s scheme must also pass.<br />7<br />
  8. 8. 8<br />Android Notifications<br />Notification message is shown on the top of the screen, to alert users that events have occurred that may require attention.<br />TheNotificationManagerclass is responsible for handling the Notifications- Its capability are<br />Create new status bar icons<br /> Display additional information (and launch an Intent) in the extended status bar window<br /> Flash the lights/LEDs<br /> Vibrate the phone<br /> Sound audible alerts (ringtones, Media Store audio)<br />
  9. 9. 9<br />Creating a Notification<br />Pending Intent<br />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). <br />This is used in setting the notification<br />Intent intent = new Intent(this, MyActivity.class);<br />PendingIntentlaunchIntent = PendingIntent.getActivity(context, 0, intent, 0);<br />setLatestEventInfo(context,expandedTitle,expandedText,launchIntent);<br />
  10. 10. Android Service<br />A Service is an application component that can perform long-running operations in the background and does not provide a user interface.<br />Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). <br /> <br />10<br />
  11. 11. A service can essentially take two forms:<br />Started – <br /><ul><li>A service is "started" when an application component (such as an activity) starts it by calling startService().
  12. 12. Once started, a service can run in the background indefinitely.
  13. 13. When the operation is done, the service should stop itself.</li></ul>Bound<br /><ul><li>A service is "bound" when an application component binds to it by calling bindService().
  14. 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). </li></ul>11<br />
  15. 15. Importance of Services and their use<br />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). <br />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. <br />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. <br />12<br />
  16. 16. Creating a Service and associating it with an Activity<br />Create a class that extends the Service class<br />Add this new Service to the manifest by adding a new service tag within the application node.<br />Override the onStartCommandand onCreate. Set the return type of the onStartCommandMethod from one of these to set the service behavior<br />a. START_STICKY<br /> b. START_NOT_STICKY<br /> c. START_REDELIVER_INTENT<br />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.<br />To stop a Service use stopService, passing an Intent that defines the Service to stop. <br />13<br />
  17. 17. Service Life Cycle<br />Mode 1 - Context.startService()<br />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.<br /> The service will at this point continue running until Context.stopService() or stopSelf() is called. <br />Mode 2 - Context.bindService() <br />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().<br /> 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<br />14<br />
  18. 18. 15<br />Android Interface Definition Language : AIDL<br />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).<br />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. <br />To create a bounded service using AIDL, follow these steps:<br />Create the .aidl file This file defines the programming interface with method signatures.<br />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.<br />Expose the interface to clients Implement a Service and override onBind() to return our implementation of the Stub class.<br />
  19. 19. Broadcast Receivers<br />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.<br />Broadcast receiver is a component that responds to system-wide broadcast announcements<br />16<br />
  20. 20. There are two major classes of broadcasts that can be received:<br />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.<br />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<br />17<br />
  21. 21. Importance of Broadcast receivers<br />Broadcast receivers are implemented In order to monitor and respond any changes in the intents which are registered with it.<br />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.<br />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<br />18<br />
  22. 22. 19<br />SQLite Databases<br />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.<br />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.<br />getWritableDatabase() and getReadableDatabase()<br />To write and read from database, their return type is SQLiteDatabase class that provides methods for database operations.<br />SQLiteDatabase query() methods – to execute queries, these methods takes various parameters, for various quires.<br />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.<br />
  23. 23. 20<br />Steps to create and read from a database <br />SQLiteDatabasemyDatabase;<br />private void createDatabase() {<br />myDatabase = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);<br />myDatabase.execSQL(DATABASE_CREATE);<br />}<br />Cursor query(SQLiteDatabase db, String[] projectionIn, String selection, String[] selectionArgs, String groupBy, String having, String sortOrder, String limit)<br />int GOLD_HOARDED_COLUMN = 2;<br />Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);<br />float totalHoard = 0f;<br />if (myGold.moveToFirst()) {<br />do {<br />float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);<br />totalHoard += hoard;<br />} while(myGold.moveToNext());<br />}<br />
  24. 24. 21<br />Content Providers<br />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<br />How to use content-providers<br />public class MyProvider extends ContentProvider {<br />@Override<br />public boolean onCreate() {<br />// TODO Construct the underlying database.<br />return true;<br />}<br />}<br />
  25. 25. 22<br />Using a Content-provider<br />We should expose a public static CONTENT_URI property that returns the full URI of this provider<br />We will use the URI matcher for this<br />public static final Uri CONTENT_URI = Uri.parse(myURI);<br />static {<br />uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);<br />uriMatcher.addURI("com.paad.provider.myApp", "items", ALLROWS);<br />uriMatcher.addURI("com.paad.provider.myApp", "items/#", SINGLE_ROW);<br />}<br />Then expose queries and transactions on our Content Provider by implementing the delete, insert,update, and query methods.<br />Register our provider by - <br /><provider android:name="MyProvider"<br />android:authorities="com.paad.provider.myapp"/><br />
  26. 26. 23<br />Using Content-Resolver<br />The Content resolver is the interface that is used to obtain the underlying data using its various abstract methods.<br />ContentResolvercr = getContentResolver();<br />// Return all rows<br />Cursor allRows = cr.query(MyProvider.CONTENT_URI, null, null, null, null);<br />// Return all columns for rows where column 3 equals a set value<br />// and the rows are ordered by column 5.<br />String where = KEY_COL3 + "=" + requiredValue;<br />String order = KEY_COL5;<br />Cursor someRows = cr.query(MyProvider.CONTENT_URI,<br />null, where, null, order);<br />
  27. 27. 24<br />References<br /><br /><br /><br /><br /><br /><br /><br /><br />
  28. 28. 25<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.