AlarmManager can't work on android 6.0

ⅰ亾dé卋堺 提交于 2019-12-07 06:16:58

问题


I am working with AlarmManager, It is not working on android os 6.0. This is my code:

 private void startAlarmManager(String id) {
    userID = GlobalValue.getUserName(GuideNavigationActivity.this);
    Context context = getBaseContext();
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    gpsTrackerIntent = new Intent(context, GpsTrackerAlarmReceiver.class);
    gpsTrackerIntent.putExtra("id", id);
    gpsTrackerIntent.putExtra("userID", userID);
    gpsTrackerIntent.putExtra("idCourse", idCourse.toString());
    gpsTrackerIntent.putExtra("typeCourse", typeCourse);
    pendingIntent = PendingIntent.getBroadcast(context, 0, gpsTrackerIntent, 0);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,System.currentTimeMillis()+ Constant.GPS_INTERVAL, pendingIntent);
    }
    else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,System.currentTimeMillis()+ Constant.GPS_INTERVAL, pendingIntent);
    } else {

        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,System.currentTimeMillis()+ Constant.GPS_INTERVAL, pendingIntent);
    }
}

Please support me. Thank so much.


回答1:


AlarmManager will not allow you to repeat that frequently, even through manual steps (e.g., setExactAndAllowWhileIdle()), on Android 5.1+.

Moreover, using AlarmManager for that frequent of an event is very inefficient, on all versions of Android. This is one of the reasons why Android no longer supports it, as too many developers were doing inappropriate things with AlarmManager and wasting users' batteries as a result.

If you need to get control every second, use some in-process solution, such as ScheduledExecutorService. Or, since your names suggest that you are tracking the location, use the appropriate APIs to let you know when the location changes, rather than trying to get control every second.



来源:https://stackoverflow.com/questions/38742368/alarmmanager-cant-work-on-android-6-0

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