根据通知设置警报



我需要向手机的时钟应用程序添加闹钟,我要向用户发送通知。当用户单击通知时,应添加具有给定时间的新警报。 下面是代码:

//Create intent
Intent alarmIntent = new Intent(AlarmClock.ACTION_SET_ALARM);
alarmIntent.putExtra(AlarmClock.EXTRA_MESSAGE, event.getEventName());
Calendar alarmTime = new GregorianCalendar();
alarmTime.setTime(new Date(event.getAlarmTime()));
alarmIntent.putExtra(AlarmClock.EXTRA_HOUR, alarmTime.get(Calendar.HOUR_OF_DAY));
alarmIntent.putExtra(AlarmClock.EXTRA_MINUTES, alarmTime.get(Calendar.MINUTE));
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
//Create and show notification
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("MyAppsAlarm",
"MyAppsAlarmNotifications",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Channel to show notifs");
mNotificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(main.getApplicationContext(), "Zzzzz")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Alarm Helper")
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(alarmPendingIntent);
mNotificationManager.notify(0, builder.build());

当我单击通知时,没有任何反应。通知抽屉自动关闭时,通知保持原样。

我尝试使用startActivity(alarmIntent);触发intent,它按预期工作,但从通知来看.setContentIntent(alarmPendingIntent);似乎什么也没做。

如果要使用AlarmClock.ACTION_SET_ALARM设置闹钟,则必须使用PendingIntent.getActvity()而不是PendingIntent.getBroadcast()AlarmClock.ACTION_SET_ALARM是一个Activity动作。

如果您不希望显示闹钟的 UI,可以将其添加到Intent

alarmIntent.putExtra(AlarmClock.EXTRA_SKIP_UI, true); 

您必须在应用中使用广播接收器才能在用户单击通知时接收广播。

让您的广播接收器成为 NotifBroadCastReceiver

public class NotifBroadCastReceiver extends BroadcastReceiver{
@override
void onReceive(Context context, Intent intent){
//you can extract info using intent.getStringExtra or any other method depending on your send data type. After that set alarm here.
}
}

因此,在创建待定意图时,您可以执行

Intent intent = new Intent(context, BroadcastReceiver.class);
//set all the info you needed to set alarm like time and other using putExtra.
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

现在,当用户单击通知时,您将在接收通知中接收广播。

注意您必须在清单中注册广播接收器,例如

<receiver
android:name="your broadcast receiver"
android:enabled="true"
android:exported="false" />

最新更新