權限:android
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
MainActivity網絡
//判斷網路是否暢通加權限 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; } }