Search code examples
androidalarmmanagerandroid-6.0-marshmallow

AlarmManager can't work on android 6.0


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.


Solution

  • 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.