on click of a status bar notification. i want to check that if my app is in foreground state then only notification will cancel or if my app is in background state it will open my app. i have managed my app state using this code in my application class
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
private static boolean activityVisible;
and putting these for all my activities
@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();
}
@Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();
}
for notification i am using this code
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(context)
.setContentTitle(title).setContentText(message)
.setSmallIcon(R.drawable.ic_on).build();
Intent notificationIntent = new Intent(context,
AppStartActivty.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
where shod i put this condition to check that app state and notification click behaviour. sorry for my bad inglish
You can check whether your app is in Background/foreground using below code.
ActivityManager activityManager = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<ActivityManager.RunningAppProcessInfo> appInfo = (ArrayList)activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo app : appInfo) {
Log.d(TAG, "App: " + app.processName + " State: " + (app.importance == 100 ? "Foreground" : "Background"));
if (app.processName.equals(YourApp().getPackageName())) {
Log.d(TAG, app.processName);
if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
// Cancel notification
}
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.