Create services never stop in Android

Today I’m going to write story on services which never stops even after closing app from background. First of all you must know that what is service in android.

What is a service in Android?

A service is a component which runs in the background without direct interaction with the user. As the service has no user interface, it is not bound to the life cycle of an activity.If you want to do some task in repetitive manner then use of service is best way.

One of the most problem occurred is service stops when you clear app from background tasks. I’m prefer broadcast receiver to do this task.

So we need service and broadcast receiver to create non stop service. when service going to stop it restarts it again by sending broadcast.

My service is below:

public class ServiceNoDelay extends Service {
public int counter = 0;
Context context;

public ServiceNoDelay(Context applicationContext) {
super();
context = applicationContext;
Log.i("HERE", "here service created!");
}

public ServiceNoDelay() {
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();

Log.i("EXIT", "ondestroy!");

Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
stoptimertask();
}

private Timer timer;
private TimerTask timerTask;

public void startTimer() {
//set a new Timer
timer = new Timer();

//initialize the TimerTask's job
initializeTimerTask();

//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}

public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ " + (counter++));
}
};
}

public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

Broadcast reciever restart service like this:

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oops!!!!");
context.startService(new Intent(context, ServiceNoDelay.class));

}
}

In manifest file ad this:

<service
android:name=".ServiceNoDelay"
android:enabled="true"
/>
<receiver
android:name=".SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
>
<intent-filter>
<action android:name="ac.in.ActivityRecognition.RestartSensor" />
</intent-filter>
</receiver>

You can add use below code to check whether service running or not. If service already in running mode then no need to start it again if not then start it in your MainActivity.

ServiceNoDelay mSensorService = new ServiceNoDelay(getApplicationContext());
Intent mServiceIntent = new Intent(getApplicationContext(), mSensorService.getClass());
if (!isMyServiceRunning(mSensorService.getClass())) {
startService(mServiceIntent);
}

Method isMyServiceRunning() is below add this in your MainActivity.

private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isMyServiceRunning?", true+"");
return true;
}
}
Log.i ("isMyServiceRunning?", false+"");
return false;
}

I hope it will help if you stuck in services. If you have questions or need help then don’t hesitate to ask.

Enjoy coding and if you like this article don’t forget to like and share it :)