屏幕锁定时,我无法使AlarmManager正常工作。无论屏幕是否被锁定,该应用程序在我的索尼爱立信Xperia Active与Android 2.3.4上运行良好。我总是在LogCat中看到调试消息onReceive()。但是当我尝试在具有更新版本Android的新设备上运行应用程序时,例如带有android 4.1.2的三星Galaxy Xcover2,该应用程序仅在屏幕打开时才有效。只要屏幕打开,我就会在LogCat中看到onReceive()的调试消息。当屏幕锁定且应用程序停止工作时,我看不到调试消息。我尝试过其他具有相同问题的设备。共同点似乎是(?)Android版本。
清单
....
<service
android:name=".MyGPSService"
android:enabled="true"
android:exported="false" >
</service>
<receiver android:name=".MyAMReceiver" />
</application>
</manifest>
主要活动
....
public void onResume() {
super.onResume();
// PendingIntent Broadcast from AlarmManager
Intent intent = new Intent(this, MyAMReceiver.class);
PendingIntent pendingintent = PendingIntent.getBroadcast(this, 112358, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Registering pending intent with AlarmManager
AlarmManager alarmmanager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmmanager.cancel(pendingintent); // Cancel any existing alarms
alarmmanager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000,60000, pendingintent); // Delay first trigger 10s, timer interval 60s
接收者类
....
public class MyAMReceiver extends BroadcastReceiver {
public MyAMReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
//DEBUG!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Log.d("MyAMReceiver", "onReceive()");
// Wake CPU from sleep if unit screen is locked
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
// Start service
Intent intentS = new Intent(context, MyGPSService.class);
context.startService(intentS);
}
}
答案 0 :(得分:0)
阅读完上述内容后,将我的代码更改为:
alarmmanager.setRepeating(AlarmManager.ELAPSE_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+10000,60000, pendingintent);
三星Android 4.1在睡觉时仍然拒绝触发AlarmManager(?)。仍然适用于索尼Android 2.3。
但根据SystemClock上的Android文档,它应该没有任何区别: “AlarmManager可以触发即使设备处于深度睡眠状态或您的应用程序未运行时发生的一次性或重复事件。可以使用您选择的currentTimeMillis()(RTC)或elapsedRealtime()(ELAPSED_REALTIME)来安排事件,并在发生时进行意图广播。“
http://developer.android.com/reference/android/os/SystemClock.html