如何从服务检查应用程序在前台?

问题描述 投票:16回答:3

只有当应用程序不在前台时,我才需要向用户显示通知。这是我的公共类MyFirebaseMessagingService扩展

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

    }

需要实施applicationInForeground()方法

android android-service
3个回答
19
投票

您可以从android系统服务控制运行的应用程序进程。试试这个:

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;
}

祝好运。


19
投票

在Google I / O 2016上,我发表了一个主题,其中一个主题是Firebase如何检测您的应用是否在前台。您可以通过为应用中的每个活动增加一个计数器来使用ActivityLifecycleCallbacks,然后为每个停止的活动递减计数器。如果计数器> 1,那么您的应用程序就在前台。可以在YouTube here上看到该演讲的相关部分。


3
投票

您也可以尝试使用Android's 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
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.