Service of an app stops when phone is not being charged

旧街凉风 提交于 2019-12-01 09:51:54

问题


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:


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.



来源:https://stackoverflow.com/questions/14924295/service-of-an-app-stops-when-phone-is-not-being-charged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!