Android编程判断网络是否可用及调用系统设置项的方法

2019-12-10 18:50:41于丽
易采站长站为您分析Android编程判断网络是否可用及调用系统设置项的方法,涉及Android针对网络连接的判定及属性设置的调用,需要的朋友可以参考下  

本文实例讲述了Android编程判断网络是否可用及调用系统设置项的方法。,具体如下:

private boolean checkNetwork() {
    boolean flag = false;
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (manager.getActiveNetworkInfo() != null)
      flag = manager.getActiveNetworkInfo().isAvailable();
    if (!flag) {
      Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage(
          "请开启GPRS或WIFI网络连接");
      b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
          Intent mIntent = new Intent("/");
          ComponentName comp = new ComponentName("com.android.settings",
              "com.android.settings.WirelessSettings");
          mIntent.setComponent(comp);
          mIntent.setAction("android.intent.action.VIEW");
          startActivity(mIntent);
        }
      }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
          dialog.cancel();
        }
      }).create();
      b.show();
    }
    return flag;
}

权限是少不了的:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


注:相关教程知识阅读请移步到Android开发频道。