Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

android - AlarmManager setExact with WakefulBroadcastReceiver sometimes not exact

Using Android 19+

setExact in conjuction with WakefulBroadcastReceiver sometimes does not fire on time (can be a few seconds or so late). I mean most it of the time it does. probably 49 times out of 50 its correct.

I'm not sure if its just because the system is busy at the time and it can't handle the workload or what

Here is how I set the alarm:

  AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
  Intent intent = new Intent(AlarmReceiver.INTENT_FILTER);
  PendingIntent alarmIntent = PendingIntent.getBroadcast(context, MyApplication.ALARM_REQUEST_CODE, intent,  PendingIntent.FLAG_UPDATE_CURRENT);
  alarmMgr.setExact(AlarmManager.RTC_WAKEUP, timeToWakeUp, alarmIntent);

Here is my receiver code:

public class AlarmReceiver extends WakefulBroadcastReceiver {

public static final String INTENT_FILTER = "myfilter";

@Override
public void onReceive(Context context, Intent intent) {
    Intent service = new Intent(context, MyWakefulService.class);
    startWakefulService(context, service);

}

}

And in the WakefulService

public class MyWakefulService extends IntentService {

....

@Override
protected void onHandleIntent(Intent intent) {

....
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For Marshmallow era(?), we need some ugly codes like below... :( And "delayInMillis" param should be more than 15 minutes on the API 23. If not, system ignore the minutes less than 15 minutes.

private void registerExactAlarm(PendingIntent sender, long delayInMillis) {
    final int SDK_INT = Build.VERSION.SDK_INT;
    AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    long timeInMillis = (System.currentTimeMillis() + delayInMillis) / 1000 * 1000;     //> example

    if (SDK_INT < Build.VERSION_CODES.KITKAT) {
        am.set(AlarmManager.RTC_WAKEUP, timeInMillis, sender);
    }
    else if (Build.VERSION_CODES.KITKAT <= SDK_INT  && SDK_INT < Build.VERSION_CODES.M) {
        am.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, sender);
    }
    else if (SDK_INT >= Build.VERSION_CODES.M) {
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeInMillis, sender);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...