通知未显示在onCreate()中。

huangapple go评论68阅读模式
英文:

Notification is not shown on oncreate()

问题

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

英文:

I am trying to create a notification. But when I run, the notification is not shown.
Can someone tell me what is wrong in the below code.

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

I am trying to create a notification. But when I run, the notification is not shown.
Can someone tell me what is wrong in the below code.

答案1

得分: 0

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

英文:

I was using Android 13 and the Android 13 needs notification permission.
After giving the permission it works fine.

huangapple
  • 本文由 发表于 2023年4月7日 01:18:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定