Service of an app stops when phone is not being ch

2019-02-20 14:50发布

My Activity starts a service by calling startservice(). To simplify my problem lets say the service will be a counter, and the counter will be increased in every 10 sec.

Timer t_counter;
int counter = 0; 

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

    t_counter = new Timer();
    t_counter.schedule(new TimerTask() { 
        @Override
        public void run() {
            counter++;
            Log.d("counter: ",Integer.toString(counter));
        }}, 0, 10000);

    return Service.START_STICKY;
}   

When the phone is being charged, (or in debug mode - since I can see the the Logcat) the service works as expected. In around every 10 sec Logcat shows the debug info, whenever the app is in background or not. But when I have unplugged the phone, the service stops running after a while. Event when the app (Activity which started the service) is active. Note that service not destroyed, just put on hold, or something like this.

Because when I plug in the mobile again, the timer continues and the value of the counter is being increased from the value where I just unplugged the phone. So if the service has been destroyed then value would have been zero again. (also I debugging the lifecycle of the service, and cannot see onStartCOmmand(), onDestroy() would have been called )

I have searched solutions for it, but I think I have not het the right answer for this behavior. I know that I should use AlarmManager instead of Timer. Or it would also work if I put the service foreground by startForeground(), or maybe separate process would solve this problem. But I would like to know why my solution is working with charging. Also where can I find infos about this "idle" state of a service. (not executing timer schedules, but not destroyed) Thanks!

1条回答
淡お忘
2楼-- · 2019-02-20 15:41

You need to hold lock if your service has to be running in the background

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = 
                      pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
// when you done
wl.release();

Better way is to use AlarmManager because keep the service running all the time will drain the battery and waste the system resources.

查看更多
登录 后发表回答