0

代码正在工作,但问题是当我从设置中打开/关闭 wifi 时,切换没有更新,就像切换按钮显示打开并且 wifi 也打开但是如果我从设置中关闭 wifi,那么这个切换仍然显示如何更新切换? 编辑最终代码 sry 1st 是错字:(

   final WifiManager wifi =  (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);    
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
//registerReceiver(broadcastReceiver, itFilter);
Intent batteryStatu = getActivity().registerReceiver(null, iFilter);
  final Switch wi = (Switch) av.findViewById(R.id.switch1);
      wi.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (wi.isChecked())
            {
            wifi.setWifiEnabled(true);

        }
            else {
                wifi.setWifiEnabled(false);
            }   ;
        }
    });
4

1 回答 1

0

如果您想在 wifi 发生变化时得到系统通知,您需要一个 BroadCastReceiver:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

    public class WifiStateReceiver extends BroadcastReceiver {

        private static final String TAG = "MyNetworkStateReceiver";

        public  static final String ACTION_WIFI_CONNEXION_CHANGED = WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION;

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            Log.d(TAG, "action=" + action);

            if (intent.getAction().equals(ACTION_WIFI_CONNEXION_CHANGED)) {
                Toast.makeText(context, "Connexion changed!", Toast.LENGTH_SHORT).show();

                if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
                    // do stuff
                    Log.d(TAG, "WIFI state connected! :)");
                } else {
                    // wifi connection was lost
                    Log.d(TAG, "WIFI state disconnected! :(");
                }
            }

        }

    }

之后,您需要在您的活动中注册您的接收器:

@Override
protected void onCreate(Bundle savedInstanceState) {
     //init your UI
     //......
    wifiReceiver = new WifiStateReceiver();
    registerReceiver(wifiReceiver, new IntentFilter(WifiStateReceiver.ACTION_WIFI_CONNEXION_CHANGED));
}

@Override
protected void onDestroy() {
    unregisterReceiver(wifiReceiver);
    super.onDestroy();
}

并且不要忘记您的 AndroidManifest.xml 中的权限:

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

最后在您的 BrodcastReceiver 的 onReceive() 方法中更新您的 UI!:)

于 2013-06-06T13:22:28.287 回答