gpt4 book ai didi

android - 无法在android studio中创建通知

转载 作者:行者123 更新时间:2023-11-29 16:40:26 27 4
gpt4 key购买 nike

我试图在 Android 上创建一个通知以启动前台服务。在“startForground”方法之后,它没有显示通知,无论是在我使用的手机上还是在模拟器上。所以我尝试使用 NotificationManager 来完成它,它也对它们都不起作用。这是代码:

Notification.Builder notify = new Notification.Builder(this).setContentText("hello!")
.setStyle(new Notification.BigTextStyle().bigText("sup!"))
.setContentTitle("sup").addAction(R.drawable.ic_launcher_foreground,"hello", PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0))
.setPriority(Notification.PRIORITY_HIGH);

if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
notify.setSmallIcon(R.mipmap.ic_launcher);
}else{
notify.setSmallIcon(R.drawable.ic_launcher_foreground);
}

NotificationManager manager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "132";
String description = "132";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("132", name, importance);
channel.setDescription(description);

manager.createNotificationChannel(channel);
}

manager.notify(132, notify.build());

Toast.makeText(this, "finished", Toast.LENGTH_LONG);
setLatestAction("finished");

所以,答案是在我开发的 android 版本上,即 Oreo,您无法通过正常方式显示通知。

最佳答案

实现如下

public static final String NOTIFICATION_CHANNEL_ID = "NOTIFICATION_CHANNEL";

@Override
public void onCreate() {
createNotificationChannel(this);
Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID).setContentText("hello!")
.setStyle(new Notification.BigTextStyle().bigText("sup!"))
.setContentTitle("sup").addAction(R.drawable.ic_launcher_foreground,"hello", PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0))
.setPriority(Notification.PRIORITY_HIGH).build();
//You can do additional config during build().
startForeground(123, notification);
}

public static void createNotificationChannel(final Context context) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.debug("Adding notification channel");
CharSequence name = "name";
String description = "description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}

关于android - 无法在android studio中创建通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897428/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com