Services in Android

Android

Services in Android is the useful for running contineous the work in background. Android offers the features of the services which works even if you are not running the application and started immediately after your phone is booted.

Create a class inherited from the Service class as below

public class YourServices extends Service {

It should be override some methods as below. And you need to define the service in Mainfest file as well

public IBinder onBind(Intent intent) {  …. }

public void onCreate(){         super.onCreate(); …  }

<service android:name=”uxl.app.util.ABTrackerSender” />

After creating the  services onStartCommand, will tract if services is started.

public int onStartCommand(Intent intent, int flags, int startId) { ….. }

You can run the scheduler or TimerTask for contineous task in onStart or onCreate events.

Starting the Service if not yet started

startService(new Intent(this , YourServices.class));


 

If you need the service running after reboot of the mobile as well then you need to make BroadcastReceiver and bind this from Mainfest as below.

public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, ABTrackerSender.class);
context.startService(startServiceIntent);
}
}

You need following permission in Mainfest.xml

<uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED” />

Inside the Application in xml file Following receiver is needed.

        <receiver android:name=”com.example.MyBroadcastReceiver” >
<intent-filter>
<action android:name=”android.intent.action.BOOT_COMPLETED” />
</intent-filter>
</receiver>

 

Now you are done.  :)

 

Leave a Reply

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