0

i want to start service in android if its being killed manually by a user ,i have read a lot about this and here what i am using in my service

my service is fetching a current user location on a regular interval and its a START_STICKY service. as i have read that whatsapp is using GCM to turn on the service again if its being manually killed by the user , so i have implemented GCM too and enable the service.

but if i manually killed my service then GCM also gets stopped ( which is an obvious reason) , so i think its a MYTH that whatsapp is using GCM to restart their own service , there is no magic behind whtsapp.

i have tried restarting the service by calling startService from onDestroy but that doesnt work too.

i have tried to run service as a separate process too by using process attribute but it doesnt effect

so is there still any way to immediately restart the service if its being killed by the user itself

note: i already know that if service is being killed by the user manually , OS will restart it soon automatically if the service is START_STICKY

Hunt
  • 8,215
  • 28
  • 116
  • 256

2 Answers2

0

Actually whats app service never be stopped any time if any user stop it manually it started in very short time because of AlarmManager. use alarmmanager instead of START_STICKY flag. Your service automatically started after killed by user. check link : http://androidsamplecodes4u.blogspot.in/2012/08/start-service-with-alarm-manager-android.html

Jayesh Khasatiya
  • 2,140
  • 1
  • 14
  • 15
  • if i am killing the service manually how my AlaramManager will gonna know when to restart as it might get killed with the processes attached with the app itself – Hunt May 27 '14 at 06:26
  • have you check above link example? there are pendingintent use. in pending intent you have to set interval after that interval your service call if you set interval to 1 mnt and set alrmmngr.setrepeating(...,pendingintent) then your service call after every 1 mnt... – Jayesh Khasatiya May 27 '14 at 06:30
0

override this method in your service hope it works

@Override
public void onTaskRemoved(Intent rootIntent) {
    Intent restartService = new Intent(getApplicationContext(),
            this.getClass());
    restartService.setPackage(getPackageName());
    PendingIntent restartServicePI = PendingIntent.getService(
            getApplicationContext(), 1, restartService,
            PendingIntent.FLAG_ONE_SHOT);

    //Restart the service once it has been killed android


    AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);

}
Preethi Rao
  • 5,117
  • 1
  • 16
  • 29