英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论