Android service runs in different mode with help of flag e.g START_CONTINUATION_MASK, START_NOT_STICKY. It enable to control the behavior of Android service life. But service will work until user allow it work. If he/she stops it, it will destroy automatically. More than often, we required it to run unstoppable If in case user stop, re-instance the old service instance.
For some people, it may malware but sometimes we have to full filled client requirement and that's all our purpose is.
Case when your service can be stopped
- User stop it forcefully
- Low Memory situation
- Device restarted
Handling first two case
When ever we stop service forcefully (or os kill it), it will call onDestory() method. First concept is to use one receiver and send one broadcast whenever service destroy. And restarted service again.
Third case if device is restarted then already we had onBootCompleted action for receiver to catch
Lets go steps by Step to make our Android Service unstoppable
Step 1) Create one Android BroadCastReciever and register it for two action
Manifest
<service android:name="ServiceTest" >
</service>
<receiver android:name="ReceiverCall" >
<intent-filter>
<action android:name="com.android.techtrainner" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
com.android.techtrainner is the custom action. BroadCastReceiver Class contain code to restart service again
public class ReceiverCall extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Service Stops", "Ohhhhhhh");
context.startService(new Intent(context, ServiceTest.class));;
}
}
Step 2) Create Android service class , do some task there (I have taken one Timer to print Log) and in onDestory()
public void onDestroy() {
try {
mTimer.cancel();
timerTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent("com.android.techtrainner");
intent.putExtra("yourvalue", "torestore");
sendBroadcast(intent);
}
Run your application and go to setting, See running service, you will TestService. Try to close it , ohhhhhh it will not close.
1 comments:
Thanks for sharing,this blog makes me to learn new thinks.
interesting to read and understand.keep updating it.
Android Training Institute in Chennai | Android Training Institute in anna nagar | Android Training Institute in omr | Android Training Institute in porur | Android Training Institute in tambaram | Android Training Institute in velachery
Post a Comment