android - 如何在 BroadcastReceiver 中知道 App 是否在前台运行?

标签 android broadcastreceiver foreground

我在需要每晚进行同步的应用程序中工作。我使用在我想要的时间调用 BroadcastReceiver 的警报管理器。问题是如果应用程序在前台运行以避免丢失数据,我无法进行同步。所以我需要在 Broadcast Receiver 中知道应用程序是否在前台运行以取消此同步。

我尝试了在 StackOverflow 中找到的解决方案: Checking if an Android application is running in the background 但是这个参数在BroadcastReceiver中始终为false,在activites中为true。

谁能告诉我是哪个问题?我做错了什么?

非常感谢!

最佳答案

尝试这种方式希望这对你有用

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (isAppForground(context)) {
            // App is in Foreground
        } else {
            // App is in Background
        }
    }

    public boolean isAppForground(Context mContext) {

        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(mContext.getPackageName())) {
                return false;
            }
        }

        return true;
    }

}

添加此权限

<uses-permission android:name="android.permission.GET_TASKS" />

关于android - 如何在 BroadcastReceiver 中知道 App 是否在前台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561823/

相关文章:

android - 如何挂载加密的APK扩展文件?

java - 无法在 Android 上接收 UDP 数据包?

android - 如何检查 Receiver 是否在 Android 中注册?

android - 如何以编程方式使用 BroadCastReceiver

iphone - 在 iOS 上收到通知时确定应用程序是否在前台运行

android - 在Android模拟器上使用录音机

android - 如何在Gradle多模块项目中使用ObjectBox?

java - 如何在前台启动文件?

android - 将相机移动到 map View 上的某个位置

Android后台服务判断前台应用