【问题标题】:Check For Internet Connection in android在android中检查互联网连接
【发布时间】:2015-04-29 06:10:16
【问题描述】:

我正在开发一个检查互联网是否可用的应用程序...

我正在从 this 获得帮助。

这是我的连接类:

  public class ChechConnection {

private Context _context;

public ChechConnection(Context context){
    this._context = context;
}

public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.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)
                  {
                      return true;
                  }

      }
      return false;
}
}

我正在使用此代码进行检查: 这是充值活动类的代码

ChechConnection cDetactor;
Boolean isInternetPresent = false;

如果有人点击一个按钮,如果有互联网连接,它应该会显示一些东西。

 cDetactor=new ChechConnection(getApplicationContext());
 isInternetPresent = cDetactor.isConnectingToInternet();


   btn_recharge.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
         if (isInternetPresent){
        Toast.makeText(mContext,"Button Pressed",Toast.LENGTH_LONG).show();
        }
        else
            alert.showAlertDialog(mContext,"Check Connection","Check Your Connection Setting",false);
    }
});

这是我自己的对话管理器:

公共类 ALertDialogManager {

public void showAlertDialog(final Context context, String title, String message,
        Boolean status) {
    final Dialog alertDialog = new Dialog(new ContextThemeWrapper(context, android.R.style.Theme_Translucent));
    alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    alertDialog.setCancelable(true);
    alertDialog.setContentView(R.layout.dialog);
    alertDialog.setTitle(title);

   Button ok=(Button) alertDialog.findViewById(R.id.btncancel);
   Button cancel=(Button) alertDialog.findViewById(R.id.btnsearch);
   ok.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        Activity activity=(Activity) context;
        activity.finish();
    }
});
   cancel.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        alertDialog.dismiss();
    }
});

    alertDialog.show();
}

}

但如果有 Internet 连接,它会给我一个错误。请检查我的 logcat 值:

04-29 11:26:15.011: E/AndroidRuntime(2177): Process: com.example.lifegoal, PID: 2177
04-29 11:26:15.011: E/AndroidRuntime(2177): java.lang.NullPointerException: Attempt to invoke virtual method 'void com.lifegoal.eshop.helper.ALertDialogManager.showAlertDialog(android.content.Context, java.lang.String, java.lang.String, java.lang.Boolean)' on a null object reference
04-29 11:26:15.011: E/AndroidRuntime(2177):     at com.lifegoal.eshop.Recharge_Activity$1.onClick(Recharge_Activity.java:51)

但如果有 Internet 连接,它会转到 else 部分并给我那个 logcat 值

谢谢!

【问题讨论】:

  • Recharge_Activity 的第 51 行有什么内容?
  • alert is null 检查“alert”对象
  • @PareshMayanin 再次检查我编辑过的内容
  • 是的,现在我有互联网连接它不应该进入其他部分@Prachi
  • 我认为mContext 为空,请检查

标签: android android-alertdialog android-logcat android-context android-internet


【解决方案1】:

使用这个方法:

public static boolean isDeviceOnline(Context context) {
        boolean isConnectionAvail = false;
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if(netInfo != null)
            return netInfo.isConnected();
            else 
                return isConnectionAvail;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isConnectionAvail;
    }

【讨论】:

    【解决方案2】:

    这是很常见的问题,每次都按照逐行教程进行。我认为您可能忘记了变量 cDetector 的初始化。并始终遵循编码标准,这样您就可以消除这样的错误。

    【讨论】:

    • @Tufan 查看答案
    【解决方案3】:
    ConnectivityManager connMgr = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    
        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean connection_check = isConnectingToInternet();
        if (connection_check) {
            newuser.setEnabled(false);
            spinner.setVisibility(View.VISIBLE);
    }
    
        else 
            Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT)
                    .show();
    
    
    
    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) 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) {
    
                        return true;
                    }
    
        }
        return false;
    }
    

    我认为是这样。可以帮助你

    【讨论】:

      【解决方案4】:

      创建一个类NetworkInformation.java

      import android.content.Context;
      import android.net.ConnectivityManager;
      import android.net.NetworkInfo;
      
      public class NetworkInformation {
      
           private static NetworkInfo networkInfo;
      
           public static boolean isConnected(Context context) {
      
                   ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
      
                   try{
                      networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
      
                  // test for connection for WIFI
                  if (networkInfo != null
                          && networkInfo.isAvailable()
                          && networkInfo.isConnected()) {
                      return true;
                  }
      
                  networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                  // test for connection for Mobile
                  if (networkInfo != null
                          && networkInfo.isAvailable()
                          && networkInfo.isConnected()) {
                      return true;
                  }
      
                  return false;
            }
      
      
      
      
      }
      

      现在通过以下代码使用该类检查互联网是否存在

       if(NetworkInformation.isConnected(Login.this)) 
                       {
                          //your code
                       }else{
                           Toast.makeText(Login.this,"No network connection",Toast.LENGTH_LONG).show();
                       }
      

      另外不要忘记在AndroidManifest.xml 中定义以下权限:

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

      【讨论】:

        【解决方案5】:

        这个方法很好用:

        public boolean checkInternetConnection(){
              ConnectivityManager connec = 
                      (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
        
          // Check for network connections
           if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
        
               // if connected with internet
        
        
               return true;
        
           } else if (
             connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
             connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
        
        
               return false;
           }
         return false;
        
        }
        

        别忘了AndroidManifest.xml。您必须定义权限:

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

        祝你编码顺利)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-16
          • 2016-08-28
          相关资源
          最近更新 更多