权限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Maintity
//判断网路是否畅通加权限 if(NetWorkUtil.isNetAvailable(MainActivity.this)){//网络畅通 //开始请求数据 }else{ Toast.makeText(MainActivity.this, "目前没网请检查网络权限", 0).show(); }
NetWorkUtil
public class NetWorkUtil { public static boolean isNetAvailable(Context context){ //获得网络管理器 ConnectivityManager connM = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = connM.getActiveNetworkInfo();//得到网络详情 if(netInfo == null || !netInfo.isAvailable()) return false; return true; } }