Service of an app stops when phone is not being charged

后端 未结 1 1926
囚心锁ツ
囚心锁ツ 2021-01-16 13:16

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 ever

相关标签:
1条回答
  • 2021-01-16 13:44

    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.

    0 讨论(0)
提交回复
热议问题