通知在oncreate()中不显示



我正在尝试创建一个通知。但是当我运行时,通知没有显示。谁能告诉我下面的代码有什么问题?

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.content.res.ResourcesCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "all_notifications";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NotificationManager nm =  (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channelN = new NotificationChannel(CHANNEL_ID, "New Channel", NotificationManager.IMPORTANCE_HIGH);
nm.createNotificationChannel(channelN);
notification = new Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.small_icon)
.setContentText("New Message")
.setSubText("subText")
.setChannelId(CHANNEL_ID)
.build();
}
else
{
notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.small_icon)
.setContentText("New Message")
.setSubText("subText")
.build();
}
nm.notify(1245, notification);
}
}

我正在尝试创建通知。但是当我运行时,通知没有显示。谁能告诉我下面的代码有什么问题?

我使用的是Android 13,而Android 13需要通知权限。在给予许可后,它工作正常。

最新更新