//加权限: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
/*
* 判断网络连接是否已开
* true 已打开 false 未打开
* */
public static boolean isConn(Context context){
boolean bisConnFlag=false;
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if(network!=null){
bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
}
return bisConnFlag;
}
/**
* 当判断当前手机没有网络时选择是否打开网络设置
* @param context
*/
public static void showNoNetWorkDlg(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.mipmap.ic_launcher) //
.setTitle(R.string.app_name) //
.setMessage("当前无网络").setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到系统的网络设置界面
Intent intent = null;
// 先判断当前系统版本
if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
context.startActivity(intent);
}
}).setNegativeButton("知道了", null).show();
}
判断网络可用从网络请求数据,并解析
请求网络的工具类
public static void getconnection(Context context, final String path, final CallJsonBack jsonBack){
if (NetPanduan.isConn(context)){
Toast.makeText(context,"网络可用",Toast.LENGTH_SHORT).show();
AsyncTask<Void,Void,String> asyncTask=new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
try {
URL url=new URL(path);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode==200){
InputStream inputStream = connection.getInputStream();
String json = streamToString(inputStream, "utf-8");
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
jsonBack.getcallBack(s);
}
};
asyncTask.execute();
}else{
NetPanduan.showNoNetWorkDlg(context);
}
}
private static String streamToString(InputStream inputStream, String s) {
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
try {
String len;
StringBuilder b=new StringBuilder();
while ((len=br.readLine())!=null){
b.append(len);
}
br.close();
return b.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
接口回调
public interface CallJsonBack {
public void getcallBack(String json);
}