我在需要每晚进行同步的应用程序中工作。我使用在我想要的时间调用 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/