获取网络状态ConnectivityManager
//获取ConnectivityManager对象。
ConnectivityManager mana = getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo对象用来描述网络信息。 //得到当前使用的网络 NetworkInfo activeNetworkInfo=mana.getActiveNetworkInfo(); //得到所有网络 NetworkInfo[] infos = mana.getAllNetworkInfo(); //获取首选网络 int networkType = mana.getNetworkPreference(); -----代码实现------- manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo(); if(activeNetworkInfo==null||!activeNetworkInfo.isAvailable()){ Toast.makeText(getApplicationContext(), "网络连接不可用", Toast.LENGTH_SHORT).show(); }else{//可能联网 int networkType = activeNetworkInfo.getType(); if(networkType == ConnectivityManager.TYPE_WIFI){ Toast.makeText(getApplicationContext(), "当前成功连接WIFI" +activeNetworkInfo.isConnected(), Toast.LENGTH_SHORT).show(); }else if(networkType==ConnectivityManager.TYPE_MOBILE){ if(activeNetworkInfo.isRoaming()){ Toast.makeText(getApplicationContext(), "当前成功连接漫游3G网络" +activeNetworkInfo.isConnected(), Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), "当前成功连接非漫游3G网络" +activeNetworkInfo.isConnected(), Toast.LENGTH_SHORT).show(); } } }
添加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>