我对设置闹钟有点困惑。如果有人可以给出反馈或一些提示,那将非常感激。总结这里是我的情况:
在我的应用程序中,我设置了一个警报:
////////////////////////
// Set an alarm
// Actually I set a unique id here. The hardcoded value is for simplicity only.
int id = 123454321;
Intent intent = new Intent(context, MyAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, id, intent, 0);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 10*1000;
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 15*1000, sender);
////////////////////////
////////////////////////
// MyAlarm implementation
public class MyAlarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// Do some periodic work here
}
}
////////////////////////
当我设置闹钟时,一切都很好。当我使用命令时,我可以看到我的警报:
adb shell dumpsys alarm
即使我的应用程序进入后台,我也能看到警报。
接下来,我通过
手动终止我的应用程序设置 - 应用程序 - 管理应用程序 - - 强制停止
当我重新发出命令“adb shell dumpsys alarm”时,我看到我的闹钟消失了。这让我觉得当我的应用程序进入后台并且框架将其杀死以释放资源时,我的警报也将被终止。但是,我想要一个独立于应用程序是否正在运行的警报。有没有人提示如何做到这一点?
答案 0 :(得分:1)
我有一个应用程序设置闹钟,然后消失。
我使用的代码是:
清单:
<receiver android:name=".AlarmReceiver" android:process=":remote"></receiver>
待定内容代码:
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("ALARM_MESSAGE", alarmMessage);
PendingIntent receiverIntent =
PendingIntent.getBroadcast(context,
MyConstants.UPDATE_ALARM, intent,
pendingIntent.FLAG_UPDATE_CURRENT);
设置(实际取消旧并重置):
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(receiverIntent); // get rid of previous if unfired.
am.set(AlarmManager.RTC_WAKEUP, calcTime.afterMidnight(), receiverIntent);
pendingIntent触发接收器,接收器做一些快速工作,发送通知,然后消失。接收方不必发布通知。它可以用意图开始一个活动,做一个祝酒消息等等。
我有一个接收器,可以在启动后恢复警报。 (警报在断电时会消失。)
答案 1 :(得分:0)
我猜你的接收器对象尚未在清单中注册。如果您在清单文件中注册了接收方对象,那么即使您的应用程序没有运行,系统也会找到它并进行调用。