-1

i'm amateur in android and i want show notification with my app.

this is my code: but does not show notification.

please help me. thanks

public class MainActivity extends AppCompatActivity {

    Button btn_ok;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_ok = findViewById(R.id.btn_ok);

        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                NotificationCompat.Builder mbuilder = (NotificationCompat.Builder)
                        new NotificationCompat.Builder(getApplicationContext())
                                .setSmallIcon(R.drawable.ic_launcher_background, 10)
                                .setContentTitle("Notification")
                                .setContentText("This is a notification for you");

                NotificationManager notificationManager = (NotificationManager)
                        getSystemService(NOTIFICATION_SERVICE);
                notificationManager.notify(0, mbuilder.build());


            }


        });


    }
}

1 Answers1

0

By default, notification shows only if the app in the background. In case if you want to show notification while app is in the foreground(currently open), you should use heads-up notification, just set HIGH_IMPORTANCE for the notification channel.

try this code, inside the clickListener method:

        val channelId = "channelId"
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_HIGH))
        notificationManager.notify(
            0, NotificationCompat.Builder(applicationContext, channelId)
                .setSmallIcon(R.drawable.ic_btn_speak_now, 10)
                .setContentTitle("Notification")
                .setContentText("This is a notification for you").build()
        )

It works in my case.

Anatolii Chub
  • 1,228
  • 1
  • 4
  • 14