我不想在应用运行或打开时显示通知。我正在使用一个报警管理器服务来构建通知我的android工作室。当应用程序打开时我收到通知。所以我想阻止这件事。并且只有当应用程序是后台或被杀时才需要通知
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**
}
}