简体   繁体   English

在Android中检查互联网连接

[英]Check For Internet Connection in android

I'm developing an application which check internet is available or not... 我正在开发一个可以检查互联网是否可用的应用程序...

I'm getting help from this . 我是从得到帮助这个

Here is my connection class : 这是我的连接类:

  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;
}
}

And I am using this code for checking : This Is Code For Recharge Activity Class 我正在使用此代码进行检查:这是充值活动类的代码

ChechConnection cDetactor;
Boolean isInternetPresent = false;

If anyone click on a button it should display something if there is an Internet connection. 如果有人单击某个按钮,则如果存在Internet连接,它应该显示一些内容。

 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);
    }
});

This is my own dialog manager : 这是我自己的对话框管理器:

public class ALertDialogManager { 公共类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();
}

} }

But if there is an Internet connection, it gives me an error. 但是,如果有Internet连接,它会给我一个错误。 Please check my logcat value : 请检查我的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)

but if there is an Internet connection, it goes to else part and gives me that logcat value 但是如果有Internet连接,它会转到其他部分并为我提供logcat的价值

Thanks! 谢谢!

use this method : 使用此方法:

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;
    }

It is very common problem, Every time follow line by line tutorials. 这是一个非常普遍的问题,每次都遵循逐行教程。 I think you may forgot initialization of your variable cDetactor. 我认为您可能忘记了变量cDetactor的初始化。 And always follow coding standers so you will eliminate your mistakes like this. 并且始终遵循编码标准,这样您就可以避免出现这样的错误。

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;
}

I think this. 我认为这。 can help you 可以帮助你

Create a class NetworkInformation.java 创建一个类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;
      }




}

Now use the class to check internet present or not by the following code: 现在,通过以下代码使用该类来检查是否存在互联网

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

Also dont forget to define the following permissions in AndroidManifest.xml: 同样不要忘记在AndroidManifest.xml中定义以下权限

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

This method works fine: 此方法工作正常:

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;

}

And dont forget about AndroidManifest.xml . 并且不要忘记AndroidManifest.xml You have to define permissions: 您必须定义权限:

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

Good luck with coding). 祝您编程愉快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM