scheduling alarm for every second in android 5.1

后端 未结 7 2236
醉梦人生
醉梦人生 2020-12-05 20:04


I want to run alarm service for every second in my application.It is working fine below 5.1 version. but it is not triggering in 5.1 devices. I am using commonsware wa

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 20:43

    This is a reported issue for Android 5.1 that happens whenever you try to set an alarm for an interval less than 60000 milliseconds.

    This warning happens because setting a very low interval like this will drain your battery very fast.

    Project member on the platform said:

    Speaking very generally: short-period and near-future alarms are startlingly costly in battery; apps that require short-period or near-future work should use other mechanisms to schedule their activity.

    That's why it is not recommended to use Alarm in your case.

    According to your Question update. You want to keep your background service Awake even if the user manually swiped it from the recent apps list. This can be done simple using the START_STICKY flag such as the following. Add this code to your service in onStartCommand method:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
    } 
    

    Source: answer

提交回复
热议问题