Я пытаюсь реализовать NotificationChannel и WorkManager, но почему-то он не работает, и я не вижу ничего неправильного - PullRequest
0 голосов
/ 05 октября 2019

Я пытаюсь реализовать функцию, при которой вы выбираете дату и время, и на вашем телефоне появляется уведомление. поэтому после написания некоторого кода он все еще не работает, но все выглядит нормально

Код активности

FloatingActionButton fab = findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.M)
                @Override
                public void onClick(View view) {

                    Calendar customCalendar = GregorianCalendar.getInstance();
                    DatePicker dp = findViewById(R.id.date_picker);
                    TimePicker picker = findViewById(R.id.time_picker);
                    customCalendar.set(
                            dp.getYear(), dp.getMonth(), dp.getDayOfMonth(), picker.getHour(), picker.getMinute(), 0);

                    long customTime = customCalendar.getTimeInMillis();
                    SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.notification_schedule_pattern), Locale.getDefault());
                    long currentTime = System.currentTimeMillis();

                    Log.d("time", "cistomTime " + customTime);
                    Log.d("time", "cistomTime " + currentTime);
                    if (customTime > currentTime) {
                        Data data = new Data.Builder().putInt(NOTIFICATION_ID, 0).build();
                        int delay = (int) (customTime - currentTime);

                        scheduleNotification(delay, data);
                        String titleNotificationSchedule = getString(R.string.notification_schedule_title);
                        Snackbar.make(
                                view,
                                titleNotificationSchedule + sdf
                                        .format(customCalendar.getTime()),
                                LENGTH_LONG).show();
    //        Snackbar.make(coordinatorLayout, "Reminder set", LENGTH_LONG)
    //                .setAction("Action", null).show();
                    } else {
                        String errorNotificationSchedule = "Error occured";
                        Snackbar.make(coordinatorLayout, errorNotificationSchedule, LENGTH_LONG).show();
                    }
                }


            });
        }

        private void scheduleNotification(long delay, Data data) {
            OneTimeWorkRequest notificationWork = new OneTimeWorkRequest.Builder(NotifyWork.class)
                    .setInitialDelay(delay, MILLISECONDS).setInputData(data).build();

            WorkManager instanceWorkManager = WorkManager.getInstance(getApplicationContext());
            instanceWorkManager.beginUniqueWork(NOTIFICATION_WORK, REPLACE, notificationWork).enqueue();
        }


    Worker class
    public class NotifyWork extends Worker {
        public static final String NOTIFICATION_ID = "notification_id";
        public static final String NOTIFICATION_NAME = "Remember";
        public static final String NOTIFICATION_CHANNEL = "Reminder_Channel";
        public static final String NOTIFICATION_WORK = "Notification_Work";

        public NotifyWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
            super(context, workerParams);
        }

        @NonNull
        @Override
        public Result doWork() {
            int id = getInputData().getInt(NOTIFICATION_ID, 0);
            sendNotification(id);
            return Result.success();
        }

        private void sendNotification(int id) {
            NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            Bitmap bitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.ic_done_white_24dp);
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra(NOTIFICATION_ID, id);
            String titleNotification = "Reminder";
            String subtitleNotification = "Time To WakeUp";
            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL)
                    .setLargeIcon(bitmap).setContentTitle(titleNotification)
                    .setContentText(subtitleNotification).setDefaults(IMPORTANCE_DEFAULT).setSound(getDefaultUri(TYPE_NOTIFICATION))
                    .setContentIntent(pendingIntent).setAutoCancel(true);

            notification.setPriority(IMPORTANCE_MAX);
            notificationManager.notify(id, notification.build());

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {


                Uri ringtoneManager = getDefaultUri(TYPE_NOTIFICATION);
                AudioAttributes audioAttributes = new AudioAttributes.Builder().setUsage(USAGE_NOTIFICATION_RINGTONE)
                        .setContentType(CONTENT_TYPE_SONIFICATION).build();


                NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, NOTIFICATION_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                channel.enableLights(true);
                channel.setLightColor(RED);
                channel.enableVibration(true);
                channel.setSound(ringtoneManager, audioAttributes);
                notificationManager.createNotificationChannel(channel);
            }


        }

У меня есть DatePicker и TimePicker, когда вы выбираете дату и время и нажимаете накнопка FAB, вы получите уведомление в это конкретное время

1 Ответ

0 голосов
/ 07 октября 2019

каким-то образом изменив .setLargeIcon на .setSmallIcon и ссылаясь на изображение напрямую, без преобразования в растровое изображение, например .setSmallIcon (R.drawable.ic_done_white_24dp) решил проблему

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...