Установить будильник из уведомления - PullRequest
1 голос
/ 21 октября 2019

Мне нужно добавить будильник в мобильное приложение часов, для которого я отправляю пользователю уведомление. Когда пользователь нажимает на уведомление, новый сигнал тревоги должен быть добавлен с указанным временем. Ниже приведен код:

//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 ]

1 голос
/ 21 октября 2019

Вы должны использовать широковещательный приемник в своем приложении, чтобы получать широковещательные сообщения, когда пользователь нажимает на уведомление.

Пусть ваш широковещательный приемник - 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.
    }
}

Так что при создании ожидающего намерения вы можетеdo

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

Теперь, когда пользователь нажимает на уведомление, вы получаете трансляцию в onReceive NotifBroadCastReceiver.

ПРИМЕЧАНИЕ Вы должны зарегистрировать свой широковещательный приемник в манифесте, как

<receiver
        android:name="your broadcast receiver"
        android:enabled="true"
        android:exported="false" />
0 голосов
/ 21 октября 2019

Если вы хотите установить будильник с помощью AlarmClock.ACTION_SET_ALARM, тогда вам нужно использовать PendingIntent.getActvity() вместо PendingIntent.getBroadcast(). AlarmClock.ACTION_SET_ALARM - это Activity ДЕЙСТВИЕ.

Если вы не хотите, чтобы отображался пользовательский интерфейс будильника, вы можете добавить его к Intent:

alarmIntent.putExtra(AlarmClock.EXTRA_SKIP_UI, true); 
...