我正在尝试开发一款应用,让我可以在每天的特定时间设置重复闹钟,例如每天下午3点15分。到目前为止,我已经设法让它在状态栏中发送通知,以便在第一天下午3点15分发出通知,但第二天它没有引发另一个警报。以下是我编写的一些代码
设置闹钟
public void setAlert(Long taskId, Calendar when) {
Intent i = new Intent(mContext, OnAlarmReceiver.class);
i.putExtra(AlertsDbAdapter.FLD_ROWID, (long)taskId);
PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_ONE_SHOT);
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
}
唤醒设备
public static void acquireStaticLock(Context context) {
getLock(context).acquire();
}
synchronized private static PowerManager.WakeLock getLock(Context context) {
if (lockStatic==null) {
PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE);
lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
LOCK_NAME_STATIC);
lockStatic.setReferenceCounted(true);
}
return(lockStatic);
}
public WakeAlertIntentService(String name) {
super(name);
}
@Override
final protected void onHandleIntent(Intent intent) {
try {
doAlertWork(intent);
}
finally {
getLock(this).release();
}
}
设置通知
NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, AlertDisplay.class);
notificationIntent.putExtra(AlertsDbAdapter.FLD_ROWID, rowId);
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
Notification note=new Notification(android.R.drawable.stat_sys_warning, "alert", System.currentTimeMillis());
note.setLatestEventInfo(this, "Test Alert", "alert", pi);
note.defaults |= Notification.DEFAULT_SOUND;
note.flags |= Notification.FLAG_AUTO_CANCEL;
int id = (int)((long)rowId);
mgr.notify(id, note);
broadcastreceiver的代码
public class OnAlarmReceiver extends BroadcastReceiver {
private static final String TAG = ComponentInfo.class.getCanonicalName();
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Received wake up from alarm manager.");
long rowid = intent.getExtras().getLong(AlertsDbAdapter.FLD_ROWID);
WakeAlertIntentService.acquireStaticLock(context);
Intent i = new Intent(context, AlertService.class);
i.putExtra(AlertsDbAdapter.FLD_ROWID, rowid);
context.startService(i);
}
}
我在代码的某个地方遗漏了什么?
答案 0 :(得分:0)
我认为你需要一个broadcastreciever
课来了解下次何时触发警报。
请参阅此tutorial: Alarm Notification
和aslo Android的警报管理器在设备重新启动时不记得警报。 要恢复警报,您需要执行以下步骤:
<强> 1。在设置警报的活动中,还将有关每个警报的信息保存到数据库中。
<强> 2。创建一个额外的BroadcastReceiver
,在启动时调用它以重新安装警报。
要了解更多信息,请参阅API Demo's - Alarm