How to automatically restart a service even if user force close it?

后端 未结 10 837
感情败类
感情败类 2020-11-27 11:19

I want a service to run all the time in my application. So I want to restart it even if it is force closed by user. There is definitely a way to do it as apps like facebook

10条回答
  •  不知归路
    2020-11-27 11:58

    You have to create a sticky service with overriding onTaskRemoved method, where you can set an alarm service to trigger your code again.

    public class BackgroundService extends Service {
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
        }
    
        @Override
        public void onTaskRemoved(Intent rootIntent) {
            //create an intent that you want to start again.
            Intent intent = new Intent(getApplicationContext(), BackgroundService.class);
            PendingIntent pendingIntent = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5000, pendingIntent);
            super.onTaskRemoved(rootIntent);
        }
    }
    

    Also in some devices like Xiaomi, Huwaei the app gets force closed once it's removed from recent apps. This is because the manufacturers have task manager features which improve ram/battery performance.

    You can check this link for more information: https://stackoverflow.com/a/41360159/2798289

提交回复
热议问题