Search code examples
androidandroid-4.4-kitkat

How to keep service alive in android kitkat?


Hello friends i have searched a lot but not find the change in service the Google have done I need to keep my service alive.

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

    return START_STICKY;
    } 

but it not restarting the service in android 4.4.2 any idea about this?


Solution

  • You can use this for Android kitkat because they are clearing the process from the background.

     @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);
                AlarmManager alarmService = (AlarmManager) getApplicationContext()
                        .getSystemService(Context.ALARM_SERVICE);
                alarmService.set(AlarmManager.ELAPSED_REALTIME,
                        SystemClock.elapsedRealtime() + 5000, restartServicePI);
    
            }