请求者连接更改不会触发

时间:2015-07-23 19:23:19

标签: android broadcastreceiver android-wifi

我想在建立wifi连接时做点什么。 我有一个BroadcastReceiver完全可以接收NETWORK_STATE_CHANGED_ACTION和SCAN_RESULTS_AVAILABLE_ACTION,但不是SUPPLICANT_CONNECTION_CHANGE_ACTION。这个更难测试:我关闭/打开路由器。

    protected void onCreate(Bundle savedInstanceState) {

    receiverWifi = new WifiReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
            intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
            intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
            registerReceiver(receiverWifi, intentFilter);
    //...
    }

     class WifiReceiver extends BroadcastReceiver {
            public void onReceive(Context c, Intent intent) {
                final String action = intent.getAction();

                Log.d("mhp","*BroadcastReceiver: " + action")}

Manifiest.xml

  <application
        a..
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.net.wifi.SCAN_RESULTS" />
                <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
                <action android:name="android.net.wifi.STATE_CHANGE" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

AndroidManifest.xml:

  <application
        a..
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.net.wifi.SCAN_RESULTS" />
                <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
                <action android:name="android.net.wifi.STATE_CHANGE" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

1 个答案:

答案 0 :(得分:4)

即使您没有SUPPLICANT_CONNECTION_CHANGE_ACTION,在连接到wifi网络时,您肯定会获得NETWORK_STATE_CHANGED_ACTION,您可以根据自己的需要使用此操作。

在广播接收器中,执行以下操作:

String action = intent.getAction();
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action))
{
    NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if ( (netInfo.getDetailedState()==(NetworkInfo.DetailedState.CONNECTED)) )
    {
        // your wifi is connected, do what you want to do
    }
}