AlarmManager无法在Android 6.0上运行

son*_*368 5 android alarmmanager android-6.0-marshmallow

我正在使用AlarmManager,它不适用于android os 6.0.这是我的代码:

 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请支持我 非常感谢.

Com*_*are 9

AlarmManager不允许您经常重复,即使是setExactAndAllowWhileIdle()在Android 5.1+上通过手动步骤(例如).

此外,在所有版本的Android上使用AlarmManager频繁的事件是非常低效的.这是Android不再支持它的原因之一,因为太多的开发人员正在做不适当的事情AlarmManager并因此浪费用户的电池.

如果您需要每秒控制一次,请使用一些进程内解决方案,例如ScheduledExecutorService.或者,由于您的名字表明您正在跟踪位置,因此请使用相应的API让您知道位置何时更改,而不是每秒都尝试获取控制权.