gpt4 book ai didi

android - 如何在应用程序运行时停止通知?

转载 作者:行者123 更新时间:2023-11-29 23:13:11 25 4
gpt4 key购买 nike

我不想在应用程序运行或打开时显示通知。我正在使用警报管理器服务在 android studio 中构建通知。当应用程序打开时我收到通知。所以我想阻止这件事。并且仅当应用程序处于后台或被杀死时才需要通知。

private void notificationDialog() {
NotificationManager notificationManager = (NotificationManager) context1.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "tutorialspoint_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_LOW);
// Configure the notification channel.
notificationChannel.setDescription("New Message Received");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context1, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND)
.setVibrate(null)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("Tutorialspoint")
//.setPriority(Notification.PRIORITY_MAX)
.setContentTitle("New Message Received")
.setContentText("This is sample notification")
.setContentInfo("Information");
notificationManager.notify((int)System.currentTimeMillis(), notificationBuilder.build());
}

最佳答案

检查应用程序是否在前台。如果应用未处于前台模式,则仅创建通知。

public static boolean isAppForground(Context context) {

ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo info : l) {
if (info.uid == context.getApplicationInfo().uid && info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}


private void notificationDialog() {
if(!isAppForground(getApplicationContext)){

** your notification create code here**
}
}

关于android - 如何在应用程序运行时停止通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55742122/

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