androidandroid-service

How to check is app in foreground from service?


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


Solution

  • 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.