无法接收本地通知Android

时间:2018-11-17 11:07:28

标签: java android android-studio notifications

我是Android编程的新手,我正在尝试构建我的第一个应用程序。现在,我想发送本地通知。不幸的是,我无法在运行API 28及更高版本的设备上收到通知。我知道自奥利奥(Oreo)以来,通知的发送方式已发生变化,并且我包含了创建通道的代码。似乎如果我在具有较低API(例如19)的模拟器上运行该应用程序,则会收到通知。另外,如果我将代码复制到新项目中,即使在运行Android Oreo的模拟器上,我也会收到通知。项目中的哪些设置可能导致Android Oreo无法接收通知? (Logcat中没有错误)

我发送通知的代码:

public static final String CHANNEL_1_ID = "channel1";

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

    createNotificationChannels();
}

public void setNotif(View view) {
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("hey")
            .setContentText("world")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build();
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(1, notification);
}

private void createNotificationChannels() {
    // if higher than android oreo
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH);
        channel1.setDescription("This is channel 1");

        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(channel1);
    }
}

通过单击按钮可以调用setNotif方法。同样,我是Android编程的新手,所以任何建议都将对您有所帮助。甚至可以以其他方式诊断问题。谢谢!

1 个答案:

答案 0 :(得分:0)

在您的setNotif()方法中添加此支票:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)  
  notificationManager.createNotificationChannel(getNotificationChannel(context));

setNotif()方法将如下更改:

public void setNotif(View view) {
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("hey")
            .setContentText("world")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build();
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)        notificationManager.createNotificationChannel(getNotificationChannel(context));
    notificationManager.notify(1, notification);
}

getNotificationChannel()方法如下所示:

private static NotificationChannel getNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
            return null;
        CharSequence name = context.getString(R.string.app_name);// The user-visible name of the channel.
        int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(BuildConfig.APPLICATION_ID, name, importance);
        notificationChannel.setShowBadge(true);
        return notificationChannel;
    }