首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓v4锁屏AlarmManager不起作用

安卓v4锁屏AlarmManager不起作用
EN

Stack Overflow用户
提问于 2013-08-08 19:20:32
回答 1查看 1.7K关注 0票数 3

当屏幕被锁定时,我无法让AlarmManager工作。这个应用程序在我的Sony Ericsson Xperia Active和Android 2.3.4上运行得很好,无论屏幕是否锁定。我总是在LogCat中看到调试消息onReceive()。但当我尝试在搭载较新版本安卓系统的较新设备上运行这款应用程序时,比如搭载安卓4.1.2系统的三星Galaxy Xcover2,这款应用程序只能在屏幕打开时才能运行。只有在屏幕打开时,我才能在onReceive()的LogCat中看到调试消息。当屏幕被锁定并且应用程序停止工作时,我看不到调试消息。我已经尝试过其他设备,但也有同样的问题。它们的共同点似乎是(?)Android版本。

清单

代码语言:javascript
复制
....

<service
android:name=".MyGPSService"
android:enabled="true"
android:exported="false" >
</service>

<receiver android:name=".MyAMReceiver" />

</application>

</manifest>

主要活动

代码语言:javascript
复制
....

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

接收器类

代码语言:javascript
复制
....

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);

}
}
EN

回答 1

Stack Overflow用户

发布于 2013-08-09 19:33:35

在阅读了上面的内容后,我将代码更改为以下内容:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18124698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档