问题描述
我的工作中的应用,需要进行同步的每一个夜晚。我用的告警管理,调用一个BroadcastReceiver在我想要的小时。的问题是,如果应用程序在前台运行,以避免丢失数据我不能让一个同步。所以,我需要知道的广播接收器,如果应用程序在前台运行,取消此同步。
I am working in application that needs make a synchronization every night. I use Alarm Manager that calls a BroadcastReceiver at the hour that I want. The problem is that I cant make a synchronization if the application is running in foreground to avoid losing data. So I need to know in Broadcast Receiver if the app is running in foreground to cancel this synchronization.
我想,我找到了StackOverflow的解决方案:Android:在后台运行的应用程序?但是,这个参数始终是虚假的BroadcastReceiver,但真正在activites。
I tried solutions that I found in StackOverflow:Android: Is application running in background?But this parameter is always false in BroadcastReceiver, but true in activites.
谁能告诉我这是什么问题?我在做什么不好?
Can anyone tell me which is the problem? What am I doing bad?
真是感谢!
推荐答案
试试这个办法,希望这对你的作品
Try this way hope this works for you
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" />
这篇关于如何知道的BroadcastReceiver如果应用程序是在前台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!