我认为 ELAPSED_REALTIME 方法可以工作,但奇怪的是它不适用于我创建的小型测试应用程序。基本上,测试应用程序是一个小部件和一个 IntentService。小部件仅显示当前时间,而 Intent Service 获取当前时间并发送广播,小部件在 onReceive() 方法中使用该广播并更新自身。小部件当然是自定义广播操作的注册接收器。在小部件的 onEnabled() 方法中,我为 AlarmManager 初始化了警报。现在一些代码:
小部件 onEnabled():
@Override
public void onEnabled(Context c) {
super.onEnabled(c);
Intent intent = new Intent(c.getApplicationContext(), SimpleIntentService.class);
PendingIntent intentExecuted = PendingIntent.getService(c.getApplicationContext(), 45451894, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) c.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, 3000, intentExecuted);
}
小部件 onReceive():
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(ACTION_RESP)) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName thisWidget = new ComponentName(context.getApplicationContext(), Widget.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int appWidgetId : allWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getApplicationContext().getPackageName(), R.layout.widget);
String s = "";
if (intent.hasExtra("msg")) s = intent.getStringExtra("msg");
// Set the text
remoteViews.setTextViewText(R.id.textView1, s);
appWidgetManager.updateAppWidget(allWidgetIds, remoteViews);
}
}
}
SimpleIntentService onHandleIntent():
@Override
protected void onHandleIntent(Intent intent) {
Log.w("TestService", "SimpleIntentService onHandleIntent called.");
String msg = new Date().toGMTString();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(Widget.ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra("msg", msg);
sendBroadcast(broadcastIntent);
}
因此,我在运行 Android 4.2.1 的 Nexus 4 和运行 Android 4.0.4 的模拟器上对此进行了测试。在这两种情况下,SimpleIntentService 都会被创建,并且每 3 秒调用一次 onHandleIntent(),即使我手动关闭了显示器也是如此。我完全不知道为什么 AlarmManager 仍然安排警报,你有吗?!
谢谢!