Service is killed in sleep mode.Why?

前端 未结 5 1323
忘了有多久
忘了有多久 2020-12-05 20:55

I\'ve read just about every Stackoverflow answer that exists on this topic, but none of them worked.

Goal: Keep my service running 24/7, all the time

5条回答
  •  没有蜡笔的小新
    2020-12-05 21:53

    Starting from SDK 26 a Service should have its relative "MainActivity" in foreground OR this Service should be started as in foreground using "startForegroundService()". The "startForeground()" doesn't work as expected if the target SDK is 26+ but need the other way I just explained.

    After this you can use following code to Kill and restart the App from scratch (yes, even the Service is killed in this way):

    Intent mStartActivity = new Intent(context, StartActivity.class);
    int mPendingIntentId = 123456;
    PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);
    

提交回复
热议问题