javaandroidandroid-notificationsnotificationmanagernotification-channel

problem in show a notification in in real device


hi guys i created a notification for android app , my code work in virtual device but not work in real device , please help me.

public void onClick(View v){
        try {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
            builder.setSmallIcon(R.mipmap.smile);
            builder.setShowWhen(true);
            builder.setContentText("This is my first notification");
            builder.setContentTitle("My Notification");
            builder.setAutoCancel(true);
            Intent i = new Intent(MainActivity.this, SecondClass.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);
            stackBuilder.addParentStack(SecondClass.class);
            stackBuilder.addNextIntent(i);
            PendingIntent pi = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pi);
            NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            nm.notify(0, builder.build());
            Toast.makeText(getApplicationContext(),"Notification showed!",Toast.LENGTH_LONG).show();
        }
        catch (Exception e){
            Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
        }
}

Solution

  • The reason could be your emulator is less than api level 26(oreo) and your phone,the real device you are talking about is greater or equal to api level 26,from oreo onwards you need to create notification channel in order to display notifications.For more info read here.