Android判断网络开关状态
聆听者

在安卓开发中,对于项目中有需要判断网络是否开启的这个需求应该算是很常见了。今天记录下安卓如何判断网络开关的状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void checkOnNetworkBtn() {
// TODO Force the user to set the network connected.
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo_GPRS = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); //系统数据流量服务
NetworkInfo networkInfo_WIFI = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); //系统WIFI服务

if (false == networkInfo_WIFI.isConnectedOrConnecting() || false == networkInfo_GPRS.isConnectedOrConnecting()) { //如果WIFI和数据流量都未开启,则进行提示
Toast.makeText(GeoCoders.this, "网络未开启", Toast.LENGTH_LONG).show();
} else {
//to do somthing
}
}