簡體   English   中英

推送通知在android studio中不起作用

[英]push Notification is not working in android studio

您好,我需要添加推送通知以代表公司歡迎用戶,這是我的代碼,但無法正常工作

 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);

我認為您不是要創建通知頻道。 這就是為什么它不顯示通知。 Android Oreo(8.0)及更高版本要求您必須首先創建一個頻道。 請檢查下面的代碼以獲得更好的理解。

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);
        }
    }

完整的解決方案如下:

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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM