0

I'm new to developing an application. Currently, I'm working on push notification. Before this, I'm trying using Android 4.4, and the push notification work just fine. But, now I'm trying to debug on my Android 9 (Pie), but it seems like the notification does not appear.

I already try a few solutions. They suggest to use a notification channel for Android 8 and above. I have tried some of the solution from here: Previous question answer and here Previous question answer. But, I don't know why it does not work for me.

Here is my code

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

    }

}

I'm not sure what wrong with my code. Please correct me if I'm wrong.

jat
  • 27
  • 4

1 Answers1

0

this code worked for me in any API number:

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) {

    }
}
reyhane
  • 155
  • 13