如何检查应用程序是否在BroadcastReceiver

时间:2016-04-28 07:11:53

标签: android android-broadcastreceiver

我想检查我的应用程序是在后台还是在Foreground中,我还想要打开或不使用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;
}

}

有没有解决方案,帮助我, 感谢。

2 个答案:

答案 0 :(得分:0)

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

要解决此问题,请在您的BroadcastReceiver的onReceive代码中,检查您的应用是否位于前台。

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

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

答案 1 :(得分:-1)

在您的活动注册广播接收器中,检查活动是在前台还是后台。

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