How to check is app in foreground from service?

人走茶凉 提交于 2020-05-25 10:42:13

问题


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


回答1:


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.




回答2:


At Google I/O 2016, I gave a talk where one of the topics was how Firebase detects if your app is in the foreground. You can use ActivityLifecycleCallbacks for that by incrementing a counter for every activity in your app that gets started, then decrementing it for each activity that gets stopped. If the counter is > 1, then your app is in the foreground. The relevant part of the talk can be seen on YouTube here.




回答3:


You could also try using Android Jetpack lifecycle components.

public class AppFirebaseMessagingService extends FirebaseMessagingService implements LifecycleObserver {

    private boolean isAppInForeground;

    @Override
    public void onCreate() {
        super.onCreate();

        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        ProcessLifecycleOwner.get().getLifecycle().removeObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onForegroundStart() {
        isAppInForeground = true;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onForegroundStop() {
        isAppInForeground = false;
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if(isAppInForeground) {
            // do foreground stuff on your activities
        } else {
            // send a notification
        }
    }
}

See here how to import the necessary dependencies, since lifecycle is not part of the standard Android SDK.



来源:https://stackoverflow.com/questions/41295924/how-to-check-is-app-in-foreground-from-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!