Android intents, notification and broadcast recievers

25
Android Intents, Services, Notifications and Broadcast Recievers 1

Transcript of Android intents, notification and broadcast recievers

Page 1: Android intents, notification and broadcast recievers

1

Android Intents, Services, Notifications and

Broadcast Recievers

Page 2: Android intents, notification 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 –

1. An Activity or Service be started to perform an action, usually with (or on) a particular piece of data

2. Broadcast that an event (or action) has occurred3. Explicitly start a particular Service or Activity

Types of Intents

Explicit – Where the Activity or the Service class to be loaded is explicitly definedImplicit – Where an action be performed on a piece of data is requested

Page 3: Android intents, notification and broadcast recievers

3

Running an Intent Explicitly

Switching from one Activity to another

Without feedback

Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);startActivity(intent);

With Feedback

private static final int SHOW_SUBACTIVITY = 1;

Intent intent = new Intent(this, MyOtherActivity.class);startActivityForResult(intent, SHOW_SUBACTIVITY);

Page 4: Android intents, notification and broadcast recievers

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.

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

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.

Page 5: Android intents, notification and broadcast recievers

5

Native Android Actions

1. ACTION_ANSour2. ACTION_CALL3. ACTION_DELETE4. ACTION_DIAL5. ACTION_EDIT6. ACTION_INSERT7. ACTION_PICK8. ACTION_SEARCH9. ACTION_SENDTO10. ACTION_SEND11. ACTION_VIEW12. ACTION_WEB_SEARCH

Page 6: Android intents, notification and broadcast recievers

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-

1. Request code The request code that was used to launch the returning sub-Activity.2. 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.

3. Intent – The Intent used to return the packaged data

Page 7: Android intents, notification and broadcast recievers

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 Filterd sata tag. 3.1. The MIME type is the data type of the data being matched3.2. The scheme is the ‘‘protocol’’ part3.3 For a hostname to match, the Intent Filter’s scheme must also pass.

Page 8: Android intents, notification and broadcast recievers

8

Android Notifications

Notification message is shown on the top of the screen, to alert users that events have occurred that may require attention.

The NotificationManager class is responsible for handling the Notifications- Its capability are1. Create new status bar icons2. Display additional information (and launch an Intent) in the

extended status bar window3. Flash the lights/LEDs4. Vibrate the phone5. Sound audible alerts (ringtones, Media Store audio)

Page 9: Android intents, notification and broadcast recievers

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);PendingIntent launchIntent = PendingIntent.getActivity(context, 0, intent, 0);setLatestEventInfo(context,expandedTitle,expandedText,launchIntent);

Page 10: Android intents, notification and broadcast recievers

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).

Page 11: Android intents, notification and broadcast recievers

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(). Once started, a service can run in the background indefinitely. When the operation is done, the service should stop itself.

BoundA service is "bound" when an application component binds to it by calling

bindService(). 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).

Page 12: Android intents, notification and broadcast recievers

12

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.

Page 13: Android intents, notification and broadcast recievers

13

Creating a Service and associating it with an Activity

1. Create a class that extends the Service class2. Add this new Service to the manifest by adding a new service tag within the

application node.3. Override the onStartCommand and onCreate . Set the return type of the

onStartCommandMethod from one of these to set the service behaviora. START_STICKYb. START_NOT_STICKYc. START_REDELIVER_INTENT

4. 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.

5. To stop a Service use stopService, passing an Intent that defines the Service to stop.

Page 14: Android intents, notification and broadcast recievers

14

Service Life Cycle

Mode 1 - Context.startService()

1. 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.

2. The service will at this point continue running until Context.stopService() or stopSelf() is called.

Mode 2 - Context.bindService()

3. 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().

4. 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

Page 15: Android intents, notification and broadcast recievers

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:

1. Create the .aidl file This file defines the programming interface with method signatures.

2. 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.

3. Expose the interface to clients Implement a Service and override onBind() to return our implementation of the Stub class.

Page 16: Android intents, notification and broadcast recievers

16

Broadcast Receivers

A broadcast receiver is a class which extends BroadcastReceiver class 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

Page 17: Android intents, notification and broadcast recievers

17

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

Page 18: Android intents, notification and broadcast recievers

18

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

Page 19: Android intents, notification and broadcast recievers

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.

Cursor It’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.

Page 20: Android intents, notification and broadcast recievers

20

Steps to create and read from a database

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

Cursor query(SQLiteDatabase db, String[] projectionIn, String selection, String[] selectionArgs, String groupBy, String having, String sortOrder, String limit)int GOLD_HOARDED_COLUMN = 2;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());}

Page 21: Android intents, notification and broadcast recievers

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 {@Overridepublic boolean onCreate() {// TODO Construct the underlying database.return true;}}

Page 22: Android intents, notification and broadcast recievers

22

Using a Content-provider

We should expose a public static CONTENT_URI property that returns the full URI of this providerWe 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"android:authorities="com.paad.provider.myapp"/>

Page 23: Android intents, notification and broadcast recievers

23

The Content resolver is the interface that is used to obtain the underlying data using its various abstract methods.

ContentResolver cr = getContentResolver();// Return all rowsCursor 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);

Using Content-Resolver

Page 24: Android intents, notification and broadcast recievers

24

References

1. http://developer.android.com/reference/android/app/Service.html2. http://developer.android.com/reference/android/content/Intent.html3. http://developer.android.com/reference/android/content/BroadcastReceiver.html4. http://developer.android.com/reference/android/app/Notification.html5. http://developer.android.com/reference/android/app/PendingIntent.html6. http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.

html7. http://developer.android.com/reference/android/database/sqlite/SQLiteQueryBuil

der.html8. http://developer.android.com/guide/developing/tools/aidl.html

Page 25: Android intents, notification and broadcast recievers

25