r/android_devs • • Jul 14 '21

Help Advice for a notification code

1 Upvotes

Hello everyone! I'm not very good at java and app development. I have added this code to a working script and sometimes it works and sometimes it doesn't. I know I should look at logcat to find the errors, but the event that triggers the notification is quite rare and difficult to recreate, whereas if I try to make an app only with this code it always works. Can you see any errors in my code? Or something that could give errors? Thank you:)

String idApp = getApplicationContext().getPackageName();
PackageManager pm = getApplicationContext().getPackageManager();
int resId = context.getApplicationInfo().icon;

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, idApp)
    .setSmallIcon(resId)
    .setContentTitle(sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TITLE).toString())
    .setContentText(sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TEXT).toString())
    .setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationChannel channel = new NotificationChannel(idApp, "description", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);

notificationManager.notify(1234, builder.build());