Уведомления Android не отображаются - PullRequest
0 голосов
/ 13 января 2019

Я пытаюсь сделать ежедневное уведомление, которое будет показано в определенное время. К сожалению это не показывает.

Я пытался следовать парам tuto (также из developer.android.com ) и проверял похожие вопросы, которые уже задавались. Чтобы сэкономить час, я использую библиотеку Hawk.

Intent intent = new Intent(getContext(), AlarmReceiver.class);
    int notificationId = 1;
    intent.putExtra("notificationId", notificationId);

PendingIntent alarmIntent = PendingIntent.getBroadcast(getContext(), 0,
            intent,PendingIntent.FLAG_NO_CREATE);

AlarmManager alarm = (AlarmManager)  getContext().getSystemService(getContext().ALARM_SERVICE);


    switch (view.getId()) {
    int hour = timePicker.getCurrentHour();
            int minute = timePicker.getCurrentMinute();

            // Create time
            ....

            //set alarm
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime, AlarmManager.INTERVAL_DAY, alarmIntent);

            Hawk.put("notification_hour", alarmStartTime);

            break;

        case R.id.cancel_button:
//cancel notification
            break;
    }
}

и здесь класс AlarmReceiver

public class AlarmReceiver extends BroadcastReceiver {

    public AlarmReceiver () {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        sendNotification(context, intent);
    }

    private void sendNotification(Context con, Intent intent) {

        int notificationId = intent . getIntExtra ("notificationId", 1);
        String message = " message";

        Intent mainIntent = new Intent(con, MainActivity.class);
        PendingIntent contentIntent = PendingIntent . getActivity (con, 0, mainIntent, 0);

        NotificationManager myNotificationManager =(NotificationManager) con . getSystemService (Context.NOTIFICATION_SERVICE);

        Notification.Builder builder = new Notification.Builder(con);
        builder.setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle("Reminder")
            .setContentText(message)
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentIntent(contentIntent)
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_ALL);

        myNotificationManager.notify(notificationId, builder.build());
    }
}

1 Ответ

0 голосов
/ 13 января 2019

В OREO они переработали уведомления, чтобы обеспечить более простой и последовательный способ управления поведением уведомлений и настройками. Некоторые из этих изменений включают в себя:

Каналы уведомлений : Android 8.0 представляет каналы уведомлений, которые позволяют создавать настраиваемые пользователем каналы для каждого типа уведомлений, которые вы хотите отобразить. Точки уведомлений: в Android 8.0 добавлена ​​поддержка отображения точек или значков на значках средства запуска приложений. Точки уведомлений отражают наличие уведомлений, которые пользователь еще не отклонил или не применил.

Откладывание : пользователи могут откладывать уведомления, что приводит к их исчезновению на некоторое время до повторного появления. Уведомления появляются с тем же уровнем важности, с которого они впервые появились.

Стиль обмена сообщениями : в Android 8.0 уведомления, использующие класс MessagingStyle, отображают больше содержимого в свернутом виде. Вам следует использовать класс MessagingStyle для уведомлений, связанных с сообщениями. Здесь мы создали класс NotificationHelper, который требует Context в качестве параметров конструктора. Переменная NOTIFICATION_CHANNEL_ID была инициализирована, чтобы установить для channel_id значение NotificationChannel.

Метод createNotification (…) требует параметров заголовка и сообщения, чтобы задать заголовок и текст содержимого уведомления. Чтобы обработать событие щелчка уведомления, мы создали объект pendingIntent, который перенаправляет на SomeOtherActivity.class.

Каналы уведомлений позволяют вам создавать настраиваемый пользователем канал для каждого типа уведомлений, которые вы хотите отобразить. Таким образом, если версия для Android больше или равна 8.0, мы должны создать объект NotificationChannel и установить для него свойство-установщик createNotificationChannel (…) объекта NotificationManager.

public class NotificationHelper {

private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static final String NOTIFICATION_CHANNEL_ID = "10001";

public NotificationHelper(Context context) {
    mContext = context;
}

/**
 * Create and push the notification 
 */
public void createNotification(String title, String message)
{    
    /**Creates an explicit intent for an Activity in your app**/
    Intent resultIntent = new Intent(mContext , SomeOtherActivity.class);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
            0 /* Request code */, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(false)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(resultPendingIntent);

    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
    {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert mNotificationManager != null;
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }
    assert mNotificationManager != null;
    mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
}

Просто включите NotificationChannel и установите для него идентификатор канала.

...