开发者

Android terminate wifi ability within application

开发者 https://www.devze.com 2023-03-10 21:14 出处:网络
One of the major requirments of my application is using cellular internet connection only. In case of detecting wifi connection, the application have to disable the wifi ability and c开发者_高级运维on

One of the major requirments of my application is using cellular internet connection only. In case of detecting wifi connection, the application have to disable the wifi ability and c开发者_高级运维onnecting through the cellualr internet connection. How it can be done? Thanks, Eyal.


Checking WIFI connection

You can use the following code to check if the active network (if any - do some null checks here) is of type WIFI.

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connManager.getActiveNetworkInfo();
if (netInfo!=null) {
    // detect type using netInfo.getType()
}

There's a TYPE_WIFI int constant in ConnectivityManager that you can use for your check. (getType returns an int to identify the network type).

More info on the Activity Manager can be found on the Android dev site.

Disabling WIFI

n order to disable the WiFi state, you have to grant the following permission in the application manifest

android.permission.CHANGE_WIFI_STATE

You can then use the WifiManager to set enable/disable the WIFI.

WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);

More info on http://developer.android.com/reference/android/net/wifi/WifiManager.html

For a complete sample, check the following post : http://android-er.blogspot.com/2011/01/turn-wifi-onoff-using.html

0

精彩评论

暂无评论...
验证码 换一张
取 消