Program Resource

Resource libraries for programmers and developers

Getting / setting Wifi in Android is easy.

First, set permission in manifest.

<uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot;/>
 <uses-permission android:name=&quot;android.permission.CHANGE_WIFI_STATE&quot;/>

CHANGE_WIFI_STATE is not needed when only getting status. Now, simple code.

WifiManager wifi;

public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	wifi = (WifiManager)getSystemService(WIFI_SERVICE);
}

public boolean checkWifi() {
   	return (wifi.isWifiEnabled());
}

public void setWifi(boolean set){
	wifi.setWifiEnabled(set);
}

Since Wifi status changes realtime, register BroadcastReceiver if you want to get notified if status changes.

@Override
protected void onResume() {
	super.onResume();
	IntentFilter filter = new IntentFilter();
	filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
	registerReceiver(mBroadcastReceiver, filter);
}

@Override
protected void onPause() {
	super.onPause();
	unregisterReceiver(mBroadcastReceiver);
}

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
			int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE , WifiManager.WIFI_STATE_UNKNOWN);

			if (extraWifiState == WifiManager.WIFI_STATE_DISABLED){
    	    }
			else if (extraWifiState == WifiManager.WIFI_STATE_ENABLED){
			}
		}
	}
};
Print Friendly, PDF & Email

This post is also available in: Japanese

Leave a Reply

Your email address will not be published. Required fields are marked *


*

CAPTCHA