【问题标题】:Failed to check internet connectivity (Android)?无法检查互联网连接 (Android)?
【发布时间】:2015-03-29 17:33:18
【问题描述】:

我在我的 android 应用程序中从服务器获取数据,同时检查 Internet 连接时,应用程序在没有 Internet 连接时崩溃。我正在使用默认的 http 连接来连接服务器。

检查互联网连接的代码是:

public void onClick(View view) {
    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        //if it is connected to internet than start Another Activity.
        startActivity(new Intent(SearchActivity.this, SearchActivity.class));
    } else if (netInfo == null) {
        AlertDialog alertDialog = new AlertDialog.Builder(ListViewExample.this).create();
        alertDialog.setTitle("Connection Problem");
        alertDialog.setMessage("You are not connected to Internet");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        alertDialog.show();
    }

}

【问题讨论】:

    标签: android connectivity internet-connection


    【解决方案1】:

    确保您已在清单文件中添加此权限,

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

    【讨论】:

      【解决方案2】:

      使用此代码检查互联网连接,它检查设备上的所有互联网连接。并确保您已在清单中添加 Internet 权限。

              boolean flag=false;
              ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
              if (connectivity != null)
              {
                  NetworkInfo[] info = connectivity.getAllNetworkInfo();
                  if (info != null)
                      for (int i = 0; i < info.length; i++)
                          if (info[i].getState() == NetworkInfo.State.CONNECTED)
                          {
                              flag=true;
      
                          }
      
              }
              if(flag==true)
              {
                   startActivity(new Intent(SearchActivity.this, SearchActivity.class));
              }
              else
              {
                   AlertDialog alertDialog = new AlertDialog.Builder(ListViewExample.this).create();
              alertDialog.setTitle("Connection Problem");
              alertDialog.setMessage("You are not connected to Internet");
              alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      
                  public void onClick(DialogInterface dialog, int which) {
                      return;
                  }
              });
              alertDialog.show();
              }
      

      【讨论】:

        猜你喜欢
        • 2012-06-12
        • 1970-01-01
        • 2016-08-28
        • 2017-11-30
        • 2012-02-21
        • 2013-02-02
        • 2011-02-14
        • 2012-03-23
        • 1970-01-01
        相关资源
        最近更新 更多