AlarmManager在Android 6.0上无法使用 [英] AlarmManager can't work on android 6.0

查看:361
本文介绍了AlarmManager在Android 6.0上无法使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AlarmManager,但不适用于android os 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);
    }
}

请支持我。非常感谢。

推荐答案

AlarmManager 不允许您重复在Android 5.1及更高版本上,即使是通过手动操作(例如 setExactAndAllowWhileIdle())也是如此。

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

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

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.

如果您需要每秒获得控制权,请使用一些进程内解决方案,例如 ScheduledExecutorService 。或者,由于您的名字表明您正在跟踪位置,因此请使用适当的API在位置更改时通知您,而不是试图每秒获取控制权。

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.

这篇关于AlarmManager在Android 6.0上无法使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆