激活/取消激活自定义广播接收器

时间:2014-09-14 08:52:55

标签: android android-fragments broadcastreceiver

我在抽屉里有4个片段。

MainActivity.java (extends FragmentActicity: contains DrawerLayout)
FragmentCreate.java (extends Fragment)
MyStuffFragment.java (extends Fragment)
ActivateFragment.java (extends Fragment)
LoginFragment.java (extends Fragment)

然后我的自定义广播接收器接收器:

MyReceiver.java (extends BroadcastReceiver)

我正在尝试激活/停用(响应激活和取消激活按钮)接收器:我使用以下代码在清单中静态注册它:

    <receiver android:name="MyReceiver">
        <intent-filter>
            <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGE" />
            <action android:name="android.net.wifi.STATE_CHANGE" />
            <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
            <action android:name="android.bluetooth.adapter.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.adapter.action.ACL_DISCONNECTED" />
        </intent-filter>
    </receiver>

我用它开始(在ActivateFragment中):

ComponentName receiver = new ComponentName(getActivity().getApplicationContext(), MyReceiver.class);
PackageManager pm = getActivity().getApplicationContext().getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

或以COMPONENT_ENABLED_STATE_ENABLED停止。

问题是:我不知道如何过滤我希望接收器等待的动作。 我收到有关wifi或蓝牙更改的通知,但我只想获得其中一个,即用户在ActivateFragment中选择的那个。 我怎样才能改变接收者应该等待的动作呢?

1 个答案:

答案 0 :(得分:0)

    //create static flag  isBluetooth=true;
    public void onReceive(Context context, Intent intent) {

       this.context = context;
         if(intent==null)
            return;
       String action = intent.getAction();
       if(action.equals("your_action"){
         isBluetooth = false;
         //do somthing
       }
       else{
         if(isBluetooth){
           // do somthing
           return;
         }
         /*do your normal stuff here*/
       }
    }

//above case is allowing you to use only one action i.e mutually exclusive.if you dont want this simply remove boolean  flag