簡體   English   中英

我正在嘗試實現 NotificationChannel 和 WorkManager 但不知何故它不起作用並且沒有看到任何錯誤

[英]I am trying to implement NotificationChannel and WorkManager but somehow its not working and am not seeing anything Wrong

我正在嘗試實現一項功能,您可以在其中選擇日期和時間,並且通知會在您的手機上彈出。 所以在編寫了一些代碼之后它仍然無法正常工作,但一切似乎都很好

活動代碼

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


        }

我有一個DatePickerTimePicker ,當您 select 日期和時間並單擊 FAB 按鈕時,您會在該特定時間收到通知

以某種方式將.setLargeIcon 更改為.setSmallIcon 並直接引用圖像而不轉換為bitmap eg.setSmallIcon(R.drawable.ic_done_white_24dp) 解決了這個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM