Reputation:
I don't want to show notification when app is running or open. i am using a Alarm manager service to build notification i android studio. i am getting notification when app is open. so i want to stop this thing. and want notification only when app is background or killed.
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());
}
Upvotes: 0
Views: 2634
Reputation: 451
Check whether app is foreground or not. If app is not in foreground mode then only create notification.
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**
}
}
Upvotes: 3