简体   繁体   中英

push Notification is not working in android studio

hi i need to add push notification for welcoming the user on behalf of company here is my code but its not working

 NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
      Notification notify=new Notification.Builder
  (getApplicationContext()).setContentTitle("BergEsapes").setContentText("Kindly Login Your Account").
                            setContentTitle("User Register Succesfully").setSmallIcon(R.drawable.appicon).build();

                    notify.flags |= Notification.FLAG_AUTO_CANCEL;
                    notif.notify(0, notify);

I think you are not creating a Notification Channel. That's why it doesn't show notification. Android Oreo(8.0) and above require you have to create a channel first. Please check below code for better understanding.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setChannelId("YOUR_PACKAGE_NAME");
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                "YOUR_PACKAGE_NAME",
                "YOUR_APP_NAME",
                NotificationManager.IMPORTANCE_DEFAULT
        );
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

The complete solution as follows:

private void showNotification(String message){

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"default")
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle("Notification Title")
            .setContentText(message)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setChannelId("YOUR_PACKAGE_NAME");
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                "YOUR_PACKAGE_NAME",
                "YOUR_APP_NAME",
                NotificationManager.IMPORTANCE_DEFAULT
        );
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
    notificationManager.notify(NOTIFICATION_ID,builder.build());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM