如何从服务检查应用程序在前台? [英] How to check is app in foreground from service?

查看:60
本文介绍了如何从服务检查应用程序在前台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    }

需要实现applicationInForeground()方法

推荐答案

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

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

祝你好运.

这篇关于如何从服务检查应用程序在前台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆