Android Studio oncreate()上不显示通知

rjjhvcjd  于 2023-04-12  发布在  Android
关注(0)|答案(1)|浏览(165)

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

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

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

jdzmm42g

jdzmm42g1#

我使用的是Android 13,Android 13需要通知权限。给出权限后,它工作正常。

相关问题