从通知设置闹钟

Set alarm from notification

我需要向移动设备的时钟应用程序添加闹钟,并向用户发送通知。当用户点击通知时,应在给定时间添加新警报。 下面是代码:

//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); 看来似乎什么也没做。

当用户点击通知时,您必须在您的应用程序中使用广播接收器来接收广播。

让你的广播接收器是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);

现在当用户点击通知时,您将在 NotifBroadCastReceiver 的 onReceive 中收到广播。

注意 你必须像

一样在清单中注册你的广播接收器
<receiver
        android:name="your broadcast receiver"
        android:enabled="true"
        android:exported="false" />

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

如果不想显示闹钟的UI,可以在Intent中添加:

alarmIntent.putExtra(AlarmClock.EXTRA_SKIP_UI, true);