最好写在外面的工具类
/**
* 判断是否有网
* @param context
* @return true:有网
* false:无网
* 再清单文件添加读取网络状态的权限;
*/
public static boolean isConnection(Context context){
//连接管理类
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info!=null&&info.isConnected()){
return true;
}else{
return false;
}
}
主布局连接判断
//获取网络
boolean connection = NetWorkUtils.isConnection(MainActivity.this);
//判断网络
if(connection==false){
Toast.makeText(MainActivity.this,"网络不给力",Toast.LENGTH_SHORT).show();
}else{
new AsyncTaskUtils().execute(urlString);
}