屏幕锁定时,我无法让 AlarmManager 工作。无论屏幕是否锁定,该应用程序都可以在装有 Android 2.3.4 的 Sony Ericsson Xperia Active 上正常运行。我总是在 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);
}
}