Android 如何在BroadcastReceiver中检查应用程序是否在前台后台运行

Android 如何在BroadcastReceiver中检查应用程序是否在前台后台运行,android,android-broadcastreceiver,Android,Android Broadcastreceiver,我想检查我的应用程序是在后台还是在前台,我还想检查应用程序处于打开状态还是未使用BroadcastReceiver public class CheckRunningApplicationReceiver extends BroadcastReceiver { Context mContext; public int mId = 1000; NotificationManager mNotificationManager; @Override public void onReceive(Co

我想检查我的应用程序是在后台还是在前台,我还想检查应用程序处于打开状态还是未使用BroadcastReceiver

public class CheckRunningApplicationReceiver extends BroadcastReceiver {
Context mContext;

public int mId = 1000;
NotificationManager mNotificationManager;

@Override
public void onReceive(Context aContext, Intent anIntent) {
    mContext = aContext;
    Boolean isAppOpen = isApplicationSentToBackground(aContext);
    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    if (isAppOpen) {
        //openNotification();
    } else {
        //mNotificationManager.cancel(mId);
    }

}

private void openNotification() {// Instantiate notification with icon and
                                    // ticker message
    Notification notification = new Notification(R.drawable.ic_launcher,"Notification message!", System.currentTimeMillis());
    PendingIntent i = PendingIntent.getActivity(mContext, 0, new Intent(mContext,MainActivity.class), 0);
    notification.setLatestEventInfo(mContext, "Notification Created","Click here to see the message", i);
    notification.flags = Notification.FLAG_ONGOING_EVENT; 
    mNotificationManager.notify(mId, notification);
}

public static boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }

    return false;
}
公共类CheckRunningApplicationReceiver扩展了BroadcastReceiver{
语境;
公共int mId=1000;
通知经理通知经理;
@凌驾
接收时公共无效(上下文A文本、意图A内容){
mContext=aContext;
布尔值isAppOpen=isApplicationSentToBackground(aContext);
mNotificationManager=(NotificationManager)mContext.getSystemService(Context.NOTIFICATION\u服务);
如果(isAppOpen){
//openNotification();
}否则{
//通知经理。取消(mId);
}
}
私有void openNotification(){//使用图标和
//股票信息
通知通知=新通知(R.drawable.ic_启动器,“通知消息!”,System.currentTimeMillis();
PendingEvent i=PendingEvent.getActivity(mContext,0,新意图(mContext,MainActivity.class),0);
notification.setLatestEventInfo(mContext,“已创建通知”,“单击此处查看消息”,i);
notification.flags=notification.FLAG\u持续事件;
mNotificationManager.notify(mId,通知);
}
公共静态布尔值isApplicationSentToBackground(最终上下文){
ActivityManager am=(ActivityManager)context.getSystemService(context.ACTIVITY_服务);
列表任务=am.getRunningTasks(1);
如果(!tasks.isEmpty()){
ComponentName topActivity=tasks.get(0).topActivity;
如果(!topActivity.getPackageName().equals(context.getPackageName())){
返回true;
}
}
返回false;
}
}

有什么解决办法吗,帮帮我,
谢谢。

即使应用程序在后台,广播接收器也能工作,因为接收器拾取的事件是全局发送的,并且每个应用程序都注册以监听这些事件,而不管应用程序是否正在运行

为了解决这个问题,在BroadcastReceive的onReceive代码中,检查你的应用程序是否在前台

有一种——也是我所知道的唯一一种——持续有效的方法来做到这一点。您需要跟踪应用程序的暂停/恢复操作。确保在每个活动中都选中此项


这里有一些示例代码。在您的情况下,您需要先检查MyApplication.isActivityVisible()==true作为验证,然后再从您的BroadcastReceiver执行任何操作。

在您的活动注册表广播接收器中检查活动是否在前台或后台

StackAnswer.java
public class StackAnswer extends Activity {
    public static final int IS_ALIVE = Activity.RESULT_FIRST_USER;
    public static final String CHECK_ALIVE_ACTION = "CHECK_ALIVE_ACTION";
    private BroadcastReceiver mRefreshReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRefreshReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                Log.i("onReceive","BroadcastIntent received in MainActivity");

                // TODO:                
                // Check to make sure this is an ordered broadcast
                // Let sender know that the Intent was received
                // by setting result code to MainActivity.IS_ALIVE
                setResultCode(MainActivity.IS_ALIVE);
            }
        };
    }



    // Register the BroadcastReceiver
    @Override
    protected void onResume() {
        super.onResume();

        // TODO:
        // Register the BroadcastReceiver to receive a 
        // DATA_REFRESHED_ACTION broadcast
        IntentFilter filter = new IntentFilter();
        filter.addAction(CHECK_ALIVE_ACTION);         
        registerReceiver(mRefreshReceiver, filter);     

    }

    @Override
    protected void onPause() {

        // TODO:
        // Unregister the BroadcastReceiver if it has been registered
        // Note: To work around a Robotium issue - check that the BroadcastReceiver
        // is not null before you try to unregister it
        if(mRefreshReceiver!=null){
            unregisterReceiver(mRefreshReceiver);
        }
        super.onPause();
    }


}
从后台发送广播以检查天气活动是否活跃

   BackgroundTask.java
   public class BackgroundTask {

    private void checkIfForeground (Context mApplicationContext){
        mApplicationContext.sendOrderedBroadcast(new Intent(
                StackAnswer.CHECK_ALIVE_ACTION), null,
                new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO: Check whether the result code is not MainActivity.IS_ALIVE
                if (getResultCode() != StackAnswer.IS_ALIVE) {
                    //Background 
                }else{
                    //Foreground 
                }
            }
        }, null, 0, null, null);
    }
}

我不知道这是否有效,但你可以尝试一下。我在这篇博文中成功地使用了Steve Liles的代码:我在活动中做了一些新的更改,你在应用程序中做了这些更改。谢谢,现在一切都好了,