NotificationChannel не работает для Android 8 и выше - PullRequest
0 голосов
/ 03 мая 2020

Я новичок в разработке приложений. В настоящее время я работаю над уведомлением pu sh. До этого я пытаюсь использовать Android 4.4, а уведомления pu sh работают просто отлично. Но сейчас я пытаюсь выполнить отладку на моем Android 9 (P ie), но кажется, что уведомление не появляется.

Я уже пробовал несколько решений. Они предлагают использовать канал уведомлений для Android 8 и выше. Я попробовал некоторые решения здесь: Предыдущий ответ на вопрос и здесь Предыдущий ответ на вопрос . Но я не знаю, почему это не работает для меня.

Вот мой код

 public void onReceive(final Context context, final Intent intent) {

    nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    int notificationId = 1;
    String channelId = "channel-01";
    String channelName = "Channel Name";
    int importance = NotificationManager.IMPORTANCE_HIGH;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(
                channelId, channelName, importance);
        nm.createNotificationChannel(mChannel);
    }


    if (!intent.getExtras().getBoolean("cancel", false)) {

        this.context = context;
        prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);

        notification = new NotificationCompat.Builder(context, channelId);
        count = intent.getExtras().getInt("count");
        name = prefs.getString("name"+count, "");
        hours = prefs.getInt("hora"+count, 8);
        minutes = prefs.getInt("minuto"+count, 0);
        minutesBefore = prefs.getInt("minutesBefore", 30);


        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH)
            isScreenOn = pm.isInteractive();
        else
            isScreenOn = pm.isScreenOn();

        if (!isScreenOn) {

            @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
            wl.acquire(10000);
            @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
            wl_cpu.acquire(10000);
        }


        /**
         * notification
         */

        final Intent notificationIntent = new Intent(context, Broadcast_TakenAction.class);
        //Broadcast_TakenAction gets called when notification is clicked
        notificationIntent.putExtra("count", count);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntent(notificationIntent);
        PendingIntent pIntent = PendingIntent.getBroadcast(context, count, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        notification.setAutoCancel(true);
        notification.setLargeIcon(drawableToBitmap(ResourcesCompat.getDrawable(context.getResources(), R.drawable.notification_large_icon, null)));
        notification.setSmallIcon(R.drawable.small_icon);
        notification.setWhen(System.currentTimeMillis());
        notification.setContentTitle(name);
        notification.setContentIntent(pIntent);
        notification.setPriority(0);
        notification.addAction(R.drawable.check, "Taken", pIntent);


        if (intent.getExtras().getBoolean("shownBefore", false)) {

            Runnable delayedThreadStartTask2 = new Runnable() {
                @Override
                public void run() {
                    new Thread(
                            new Runnable() {
                                @Override
                                public void run() {

                                    for (int incr = 0; incr < minutesBefore; incr++) {

                                        if (!intent.getExtras().getBoolean("cancel", false)) {

                                            int time_left = minutesBefore - incr;

                                            notification.setContentText(time_left + "m left.");
                                            nm.notify(count, notification.build());
                                            try {
                                                Thread.sleep(60 * 1000);
                                            } catch (InterruptedException ignored) {
                                            }
                                        }
                                    }

                                    realNotification();
                                    if (prefs.getBoolean("vibrates", true)) {
                                        Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                                        v.vibrate(500);
                                    }
                                }
                            }

                    ).start();
                }
            };
            delayedThreadStartTask2.run();

        } else {
            realNotification();
        }

    }

}

Я не уверен, что не так с моим кодом. Пожалуйста, поправьте меня, если я ошибаюсь.

1 Ответ

0 голосов
/ 03 мая 2020

этот код работал для меня в любом номере API:

public void Notificate() {
    try {

            final String NOTIFICATION_CHANNEL_ID = "10001";

            String notification_title = getResources().getString(R.string.label);
            String notification_message =jsonArray.get(4).getAsString() ;

            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(ActivityMain.this)
                            .setSmallIcon(R.drawable.tahlil)
                            .setContentTitle(notification_title)
                            .setContentText(notification_message)
                            .setAutoCancel(true)
                            .setVibrate(new long[]{100, 200, 300, 400})
                            .setSound(alarmSound);

            Intent resultIntent = new Intent(getApplicationContext(), ActivityChatList.class);
            resultIntent.putExtra("menuFragment", "favoritesMenuItem");
            // resultIntent.putExtra("user_id", from_user_id);

            PendingIntent resultPendingIntent =
                    PendingIntent.getActivity(
                            getApplicationContext(),
                            0,
                            resultIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT
                    );

            mBuilder.setContentIntent(resultPendingIntent);
            int mNotificationId =  System.currentTimeMillis();
            NotificationManager mNotifyMgr =
                    (NotificationManager) getSystemService(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);

                mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
                if (mNotifyMgr != null) {
                    mNotifyMgr.createNotificationChannel(notificationChannel);
                }
            }
            if (mNotifyMgr != null) {
                mNotifyMgr.notify(mNotificationId, mBuilder.build());
            }


    } catch (Exception e) {

    }
}
...