从不调用WiFi广播接收器

时间:2015-02-06 08:31:32

标签: android broadcastreceiver android-broadcast

我尝试注册一个wifi接收器,我按照下面发布的代码所示,问题是我故意禁用设备中的wifi并运行代码Toast {{1}永远不会调用else中的语句。

BroadCast Receiver

权限

OnClickListener mainFramListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);
    }
};

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
            if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)){
                MQTT_Connection_Module();
            } else {
                Toast.makeText(getApplicationContext(), "No WiFi-Connection", Toast.LENGTH_SHORT).show();
            }
        }
    };
};

1 个答案:

答案 0 :(得分:0)

尝试这种方法:

//put this in your activity, service, or whatever

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

        boolean isWifiConnected = false;
        boolean isMobileConnected = false;

        ConnectivityManager connMgr = (ConnectivityManager) 
                context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if(networkInfo != null)
        isWifiConnected = networkInfo.isConnected();

        networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if(networkInfo != null)
        isMobileConnected = networkInfo.isConnected();  

        Log.d("network status", "wifi == " + isWifiConnected + " and mobile == " + isMobileConnected);

        }
    };

//registering the receiver from activity, service

registerReceiver(mConnReceiver, 
           new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

//or 

context.registerReceiver(mConnReceiver, 
           new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); //where context it's a Context class object


//manifest 

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



// see http://androidsnippets.com/network-connectivity-changes