如何在 BroadcastReceiver 的前台后台查看应用 运行

How to check app is running in background of foreground in BroadcastReceiver

我想检查我的应用程序是在后台还是在前台,我还想使用 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;
}

}

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

BroadcastReceiver 即使在应用程序处于后台时也能正常工作,因为接收器拾取的事件是全局发送的,并且每个应用程序都已注册以监听这些事件,无论应用程序是否 运行.

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

有一种——而且我所知道的唯一一种——始终有效的方法来做到这一点。您需要跟踪您的应用程序的 pause/resume 操作。确保在每个 activity.

中检查此项

这个 answer 中有一些示例代码。在您的情况下,您需要在从 BroadcastReceiver 执行任何操作之前检查 MyApplication.isActivityVisible() == true 作为验证。

在你的activity注册广播接收器来检查activity是在前台还是后台。

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


}

从后台发送广播以检查天气activity是否存在

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