I have started a service in an activity. When I close the activity, the activity service is also getting stop.
Is there any way to restart it automatically.?
I have started a service in an activity. When I close the activity, the activity service is also getting stop.
Is there any way to restart it automatically.?
If you want your service to run in background , without stopping it , then start your service as sticky .
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/* your code goes here */
return START_STICKY;
}
this is the worst problem, whatever you do.. you service never be restart until you open your application. but in API 21
android developer added Job Schedular to maintain background services. you can use this to schedule your services regarding time, and internet connectivity and so on.
for more information you can refer this tutorial. HAPPY CODING.
private void restartService() {
Intent restartIntent = new Intent(this, ScreenLockService.class);
PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}