Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check is app in foreground from service?

Tags:

I need to show notification to user only if application is not in foreground. Here is my public class MyFirebaseMessagingService extends

FirebaseMessagingService {     @Override     public void onMessageReceived(RemoteMessage remoteMessage) {         if(applicationInForeground()) {             Map<String, String> data = remoteMessage.getData();             sendNotification(data.get("title"), data.get("detail"));         }      } 

need to implement applicationInForeground() method

like image 566
amazingbasil Avatar asked Dec 23 '16 05:12

amazingbasil


People also ask

How do I know if an app is running in the foreground?

Whenever a new activity is started and visible to the user its instance is updated in the application class: activeActivity variable, so we can use it to determine which activity is in the foreground from the notifications layer.

What is app foreground service?

Foreground services are an advanced Android concept which allows you to display notifications to your users when running long lived background tasks. The notification acts like any other notification, however it cannot be removed by the user and lives for the duration of the service.


1 Answers

You can control running app processes from android system service. Try this:

private boolean applicationInForeground() {     ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);     List<ActivityManager.RunningAppProcessInfo> services = activityManager.getRunningAppProcesses();     boolean isActivityFound = false;      if (services.get(0).processName             .equalsIgnoreCase(getPackageName()) && services.get(0).importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {         isActivityFound = true;     }      return isActivityFound; } 

Good luck.

like image 68
Batuhan Coşkun Avatar answered Nov 15 '22 20:11

Batuhan Coşkun