0

Running this example in the Android Studio debugger in order to learn how notifications work. Version 33 of API.

@Override
public void onClick(View v) {
    // Show the notification
    Log.d("click", "clicked");
    // Create a notification channel
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                "channel_id",
                "Channel Name",
                NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
    // Build the notification
    Notification.Builder builder = new Notification.Builder(this, "channel_id")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("Notification Title")
            .setContentText("Notification Text");
    notificationManager.notify(1, builder.build());
}

Any idea why the notificationManager reference becomes null after calling notificationManager.createNotification(channel)? Do I need to still use NotificationCompat even if I'm only interested in running my code right now at API level 33?

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
StackExchanger
  • 245
  • 1
  • 6
  • 1
    I'm surprised this code compiles without error. Is there a `notificationManager` field declared on the class but not instantiated? If it is, then [there is variable shadowing inside the if-block](https://stackoverflow.com/q/4560850/2821954). – Andrew T. Mar 20 '23 at 12:08
  • Thanks. Missed the fact that Java uses block scoping. Used to function scoping in Python. – StackExchanger Apr 26 '23 at 16:03

0 Answers0