android 判断网络连接

来源:互联网 发布:linux 防火墙设置 编辑:程序博客网 时间:2024/06/11 18:35
android 判断网络连接

//网络连接
public static boolean checkNet(Context context){
  //获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
  try{
   ConnectivityManager connectivity = (ConnectivityManager)context
     .getSystemService(Context.CONNECTIVITY_SERVICE);
   if(connectivity != null){
    //获取网络连接管理的对象
    NetworkInfo info = connectivity.getActiveNetworkInfo();
    if(info != null && info.isConnected()){
     //判断当前网络是否已经连接
     if(info.getState() == NetworkInfo.State.CONNECTED){
      return true;
     }
    }
   }
  }catch(Exception e){
   e.printStackTrace();
  }
  return false;
 }

//检查网络
     public static void alertNetError(Context context){
      boolean f = NetCheck.checkNet(context);
      if(!f){
       AlertDialog.Builder ab = new AlertDialog.Builder(context);
       ab.setTitle(R.string.net500);
       ab.setMessage(R.string.net304);

//退出按钮
       ab.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
     
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      dialog.cancel();
      exitApp();
     }
    });
       //设置网络
       ab.setPositiveButton(R.string.shezhiwangluo, new DialogInterface.OnClickListener() {
     
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      dialog.cancel();
      context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
     }
    });
       ab.create().show();
      }
     }

 

//退出提示
     public static void promptExit(Context context){
      //创建对话框
      LayoutInflater li = LayoutInflater.from(context);
      View exitV = li.inflate(R.layout.exitdialog, null);
      AlertDialog.Builder ab = new AlertDialog.Builder(context);
      ab.setView(exitV);//设定对话框显示的View对象
      ab.setPositiveButton(R.string.app_exit_ok, new
      android.content.DialogInterface.OnClickListener() {
    
    public void onClick(DialogInterface arg0,int arg1) {
     // TODO Auto-generated method stub
     exitApp();//退出方法
    }
   });
      ab.setNegativeButton(R.string.app_exit_cancle, null);
      //显示对话框
      ab.show();
     }

 



强调一下:
这里必须在android配置文件中加上运行网络访问的权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

不然回报错
java.lang.SecurityException: ConnectivityService: Neither user 10034 nor current process has android