我为设置创建了一个活动,并在其中创建了一个开关,用于在上午7点和下午5点的特定时间发送通知。当我检查开关时,出现了两个通知。
开关代码是
public void OnRepeationNotification(int id,int hours,int minutes,int seconds) {
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hours);
calendar.set(Calendar.MINUTE,minutes);
calendar.set(Calendar.SECOND,seconds);
Intent intent=new Intent(getApplicationContext(),NotificationReciever.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplicationContext(),id,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager=(AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
public void onClickNotify(View view) {
Switch v=(Switch) view;
if(v.isChecked()){
putSett(true,"sett",this,0);
OnRepeationNotification(1,7,0,0);
OnRepeationNotification(2,17,0,0);
}else {
alert_sound.setChecked(false);
alert_vibrate.setChecked(false);
putSett(false,"sett",this,1);
putSett(false,"sett",this,2);
putSett(false,"sett",this,0);
}
}
广播接收器的代码
public class NotificationReciever extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
sendNotification(context,1);
sendNotification(context,2);
}
public void sendNotification(Context context,int id){
NotificationManager notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent=new Intent(context,RepeatingActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(context,id,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder=new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.fav_black)
.setContentTitle("Notifiction Title")
.setContentText("Notification Text")
.setAutoCancel(true);
notificationManager.notify(id,builder.build());
}
}
即使应用关闭或设备重启,如何发送通知?
答案 0 :(得分:0)
如果设置的时间已在当天通过,则会立即触发通知。要解决此问题,您需要检查时间是否已经过去,如果有时间,则将其添加到日历对象以设置第二天的警报:
calendar.set(Calendar.DATE, 1);
如果用户通过在“最近的应用”屏幕中将其滑开来关闭应用,则闹钟将保持有效。为了在手机重启后保持警报活动,您需要在其清单声明中使用BroadcastReceiver
意图过滤器BOOT_COMPLETED
,如下所示:
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
在BroadcastReceiver
内,您应该运行IntentService
,然后重新启动所有警报。