从通知设置警报

时间:2019-10-21 10:03:11

标签: android notifications android-pendingintent alarm

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

//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());

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

我尝试使用intent触发startActivity(alarmIntent);,它按预期方式工作,但从通知.setContentIntent(alarmPendingIntent);起似乎无济于事。

2 个答案:

答案 0 :(得分:0)

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

让您的广播接收者是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" />

答案 1 :(得分:0)

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

如果您不想显示闹钟的用户界面,则可以将其添加到Intent

alarmIntent.putExtra(AlarmClock.EXTRA_SKIP_UI, true); 
相关问题