4

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.?

Hossam Ghareeb
  • 7,063
  • 3
  • 53
  • 64
Pankaj Talaviya
  • 3,328
  • 28
  • 31

3 Answers3

1

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;
}
Mithun Sarker Shuvro
  • 3,902
  • 6
  • 32
  • 64
  • 2
    based my own experience, START_STICKY not guarantee the service to restart automatically. my case is when the user click home button on the device. then the user use other apps for example facebook, whatsapp for a minute. then if user open the app, the service already gone eventhough the service already used START_STICKY – Dika Mar 17 '17 at 04:20
0

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.

Sagar Chavada
  • 5,169
  • 7
  • 40
  • 67
-1
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);
}
Pankaj Talaviya
  • 3,328
  • 28
  • 31