当屏幕被锁定时,我无法让AlarmManager工作。这个应用程序在我的Sony Ericsson Xperia Active和Android 2.3.4上运行得很好,无论屏幕是否锁定。我总是在LogCat中看到调试消息onReceive()。但当我尝试在搭载较新版本安卓系统的较新设备上运行这款应用程序时,比如搭载安卓4.1.2系统的三星Galaxy Xcover2,这款应用程序只能在屏幕打开时才能运行。只有在屏幕打开时,我才能在onReceive()的LogCat中看到调试消息。当屏幕被锁定并且应用程序停止工作时,我看不到调试消息。我已经尝试过其他设备,但也有同样的问题。它们的共同点似乎是(?)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);
}
}发布于 2013-08-09 19:33:35
在阅读了上面的内容后,我将代码更改为以下内容:
alarmmanager.setRepeating(AlarmManager.ELAPSE_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+10000,60000, pendingintent);三星安卓4.1仍然拒绝启动AlarmManager(?)在睡觉的时候。不过,仍然可以在索尼安卓2.3上运行。
但根据安卓在SystemClock上的文档,这不应该有任何区别:“AlarmManager可以触发一次性或重复发生的事件,即使在设备处于深度睡眠或应用程序未运行时也是如此。事件可以根据您选择的currentTimeMillis() (RTC)或elapsedRealtime() (ELAPSED_REALTIME)进行计划,并在发生时引发意图广播。”
http://developer.android.com/reference/android/os/SystemClock.html
https://stackoverflow.com/questions/18124698
复制相似问题