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

时间:2019-04-18 08:33:48

标签: android notifications

我不想在应用程序运行或打开时显示通知。我正在使用警报管理器服务来在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());
    }

1 个答案:

答案 0 :(得分:0)

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

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**
    }
}