代码正在运行,但问题是当我打开/关闭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);
} ;
}
});
答案 0 :(得分: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! :)