Планирование уведомлений с диспетчером аварий - PullRequest
0 голосов
/ 31 октября 2019

Я знаю, что об этом уже спрашивали, но я до сих пор не нашел четкого ответа, потому что предыдущие ответы довольно старые. Я следовал нескольким учебникам, пробовал несколько разных способов даже показать уведомление. Ничего не помогло, и я думаю, что моя проблема в том, что я не понимаю, как использовать каналы уведомлений. Все учебные пособия, за которыми я следовал, были сделаны до Oreo, поэтому я не видел ничего полезного, и фрагменты от разработчиков Google тоже не помогают.

Так что последний учебник, за которым я следовал (или, скорее, скопировал), сказал сделать это: Этот класс создает уведомление с напоминанием диспетчера аварийных сигналов

public class NotificationService {
    public static final int DAILY_REMINDER_REQUEST_CODE = 100;
    public static final String TAG = "Service";

    private static Context context;

    public static void setContext(Context inContext) {
        context = inContext;
    }


    public static void setReminder(Context context, Class<?> cls, int hour, int min) {
        Calendar calendar = Calendar.getInstance();
        Calendar setcalendar = Calendar.getInstance();
        setcalendar.set(Calendar.HOUR_OF_DAY, hour);
        setcalendar.set(Calendar.MINUTE, min);
        setcalendar.set(Calendar.SECOND, 0);
        // cancel already scheduled reminders
        cancelReminder(context, cls);

        if (setcalendar.before(calendar))
            setcalendar.add(Calendar.DATE, 1);

        // Enable a receiver
        ComponentName receiver = new ComponentName(context, cls);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                DAILY_REMINDER_REQUEST_CODE, intent1,
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    public static void cancelReminder(Context context, Class<?> cls) {
        // Disable a receiver

        ComponentName receiver = new ComponentName(context, cls);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);

        Intent intent1 = new Intent(context, cls);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pendingIntent);
        pendingIntent.cancel();
    }

    public static void showNotification(Context context, Class<?> cls, String title, String content) {
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Intent notificationIntent = new Intent(context, cls);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(cls);
        stackBuilder.addNextIntent(notificationIntent);

        PendingIntent pendingIntent = stackBuilder.getPendingIntent(DAILY_REMINDER_REQUEST_CODE, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, createNotificationChannel());

        Notification notification = builder.setContentTitle(title)
                .setContentText(content)
                .setAutoCancel(true)
                .setSound(alarmSound)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setChannelId("10")
                .setContentIntent(pendingIntent).build();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(DAILY_REMINDER_REQUEST_CODE, notification);

    }

Этот класс является широковещательным приемником для запуска уведомления

public class NotifyPublisher extends BroadcastReceiver {
    public static final String TAG = "Publisher";

    private SharedPreferences SP;


    @Override
    public void onReceive(Context context, Intent intent) {
        SP = context.getSharedPreferences("com.STIRlab.ema_diary", Context.MODE_PRIVATE);

        if (intent.getAction() != null && context != null) {
            if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
                // Set the alarm here.
                Log.d(TAG, "onReceive: BOOT_COMPLETED");

                int hour = SP.getInt("hour", 0);
                int minute = SP.getInt("minute", 0);

                NotificationService.setReminder(context, NotifyPublisher.class, hour, minute);
                return;
            }
        }

        Log.d(TAG, "onReceive: ");

        //Trigger the notification
        NotificationService.showNotification(context, MainActivity.class,
                "30 Days", "Don't forget your daily journal entry");
    }
}

, и именно так я пытаюсь вызвать его вмой MainActivity

SP.edit().putInt("hour", 14).apply();
SP.edit().putInt("minute", 06).apply();
NotificationService.setReminder(MainActivity.this, NotifyPublisher.class, 14,06);

и да, я зарегистрировал его в своем манифесте

<receiver android:name=".Helpers.NotifyPublisher"
     android:enabled="false">
     <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED" />
     </intent-filter>
</receiver>

Ничего не появляется, и я не уверен почему.

...