同时在Nougat和Oreo上推送通知无法工作

3
我有两个与推送通知相关的函数。
对于Nougat(7.0)(不适用于高于24的版本)。
  Uri SoundUri = RingtoneManager.getDefaultUri((RingtoneManager.TYPE_NOTIFICATION));


                    Notification notification = new Notification.Builder(first.this)
                            .setVibrate(new long[] { 350, 350})
                            .setSmallIcon(R.drawable.testicon)
                            .setContentTitle("test tittle")
                            .setContentText("test content")
                            .setSound(SoundUri).build();

                    NotificationManager notifmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    notifmanager.notify(0,notification);

适用于Oreo或更高版本(8.0)(不适用于Nougat API 24)

 CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;

        String CHANNEL_ID = "my_channel_01";// The id of the channel.
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        int notifyID = 1;

        Notification notification = new NotificationCompat.Builder(this)
                .setVibrate(new long[] { 350, 350})
                .setSmallIcon(R.drawable.testicon)
                .setContentTitle("test tittle")
                .setChannelId(CHANNEL_ID).build();

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        mNotificationManager.createNotificationChannel(mChannel);

        mNotificationManager.notify(notifyID , notification);

现在我使用Gradle。

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
    applicationId "com.test.testttt"
    minSdkVersion 17
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

是否有适用于几乎所有Android版本(因此我想要使其至少在API +17上被接受)的推送通知方法/函数?

1个回答

3
如果操作系统版本是Oreo或更高版本,请设置通道并将其ID设置为通知,否则不要创建通道。在Oreo及以上版本中使用通道来显示通知。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    notification.setChannelId(CHANNEL_ID);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接