Mindmajix

Android Services

What is Service?

Android user interface is restricted to perform long running jobs to make the user experience smoother. A typical long running tasks can be periodic downloading of data from internet, saving multiple records into database, perform file I/O, fetching your phone contacts list, etc. For such long running tasks, service is the alternative.

  1. A service is an application component used to perform long running tasks in the background.
  2. A service doesn’t have any user interface, and neither can directly communicate to an activity.
  3. A service can run in the background indefinitely, even if component that started the service is destroyed.
  4. Usually a service always performs a single operation and stops itself once intended task is complete.
  5. A service runs in the main thread of the application instance. It doesn’t create its own thread. If your service is going to do any long running, blocking operation, it might cause Application Not Responding (ANR). And hence, you should create a new thread within the service.

A service is a component which runs in the background, without interacting with the user. The Android platform provides a lot of pre-defined services, usually exposed via a Manager class. In your activity, you access services via the method getSystemService().

Own Services must be declared via the “AndroidManifest.xml”. They run the main thread of their hosting process. Therefore, you should run performance intensive tasks in the background .

Own Services:

You can declare your own service to perform long running operations without user interaction or to supply functionality to other applications. An activity can start a service via the startService() method and stop the service via the stopService() method. If the activity wants to interact with the service it can use the bindService() method of the service. This requires an “ServiceConnection” object which allows to connect to the service and which return a IBinder object. This IBinder object can be used by the activity to communicate with the service.

Once a service is started, its onCreate() method is called. Afterwards the onStartCommand() is called with the Intent data provided by the activity. startService also allows to provide a flag which determines the life cycle behavior of the services. START_STICKY is used for services which are explicitly started or stopped. Services started with START_NOT_STICKY will end automatically after the onStartCommand() method is done. A service is started within the main thread of the application therefore all long running tasks should be performed in the background .

A Service needs to be declared in the “AndroidManifest.xml” via a <service android:name=”yourclasss”> </service> and the implementing class must extend the class “Service” or one of its subclasses.

One common case is that the service and the activity are very closely related. In this case, class just case the IBinder to the class the service provides.

Another example would be the usage of Remote Messenger Service. In this case, activities can send messages to the service and receive messages as well if they register for them.

Broadcast Receiver:

Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometimes called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.

A broadcast receiver is a class which extends “BroadcastReceiver” 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. “BroadCastReceiver” defines the method “onReceive()”. Only during this method, your broadcast receiver object will be valid, afterwards the Android system will consider your object as no longer active. Therefore, you cannot perform any asynchronous operation.

Pending Intent:

PendingIntent is basically an object that wraps another Intent object. Then it can be passed to a foreign application where you’re granting that app the right to perform the operation, i.e., execute the intent as if it were executed from your own app’s process (same permission and identity). For security reasons, you should always pass explicit intents to a PendingIntent rather than being implicit.

A PendingIntent is considered as a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code. To perform a broadcast via a pending intent, so as to get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via a pending intent, you receive the activity via PendingIntent.getActivity().

Broadcast Receiver Example:

We will define a broadcast receiver which listens to telephone state changes. If the phone receives a phone call then our receiver will be notified and log a message.

Create a new project “saitech.android.receiver.phone”. We do not need an activity. Create the following “AndroidManifest.xml”.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="sk.saitech.android.receiver" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"> <receiver android:name="MyPhoneReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-
permission>
</manifest>

Create the following class “MyPhoneReceiver”.

package sk.saitech.android.receiver; import android.content.BroadcastReceiver; import android.content.Context;
import android.content.Intent; import android.os.Bundle;
import android.telephony.TelephonyManager; import android.util.Log;
public class MyPhoneReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE); Log.w("DEBUG", state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) { String phoneNumber = extras
.getString(TelephonyManager.EXTRA_INCOMING_NUMBER); Log.w("DEBUG", phoneNumber);
}
}}}

If you install your application and receive a call, e.g., simulated by the DDMS perspective in Eclipse, then your receiver will be called and lot a message to the console.

 

 

 


 

0 Responses on Android Services"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.
Course Adviser

Fill your details, course adviser will reach you.