public class NetUtils { public static Boolean isConnt(Context context){ Boolean result=true; ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info!=null&&info.isConnected()){ result=true; }else{ result=false; } return result; } public static void openDia(final Context context){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("提示"); builder.setMessage("没有网络请设置网络"); builder.setPositiveButton("设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { 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); } }); builder.setNegativeButton("取消",null); builder.show(); } }
Boolean connt = NetUtils.isConnt(MainActivity.this); if (connt){ Toast.makeText(MainActivity.this,"有网络",Toast.LENGTH_SHORT); }else{ NetUtils.openDia(MainActivity.this); }