简体   繁体   English

如何在Android中检查移动网络是否连接到互联网

[英]How to check if mobile network is connected to the internet or not in android

How to check if packet data of the mobile is connected or not. 如何检查手机的分组数据是否已连接。 Because when I enable the mobile data option on my android app even without any load in my simcard it always connects. 因为当我在android应用程序上启用移动数据选项时,即使SIM卡中没有任何负载,它也始终会连接。 My problem is how to validate if the there is an internet connection or not in my android app. 我的问题是如何验证我的android应用程序中是否存在互联网连接。

btw here is my code. 顺便说一句,这是我的代码。

    ConnectivityManager cm = (ConnectivityManager)this.GetSystemService(Context.ConnectivityService);



    NetworkInfo nf = cm.ActiveNetworkInfo;
    if (nf != null && nf.IsConnected == true)
    {
//connected
    }
    else
    {
//not connected
    }

But in this code. 但是在这段代码中。 Even if i'm out of load. 即使我没有负载。 My application show i' still connected. 我的应用程序显示我仍然连接。 Help Pls.. 帮助请

Try this: 尝试这个:

boolean internetCheck;
internetCheck = isInternetAvailable(this);
if (internetCheck) {
                //Internet available
            } else {
                //No Internet available         }  
    /**
         * 
         * Method to check internet connection is available
         */

        public static boolean isInternetAvailable(Context context) {
            boolean haveConnectedWifi = false;
            boolean haveConnectedMobile = false;
            boolean connectionavailable = false;

            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();

            NetworkInfo informationabtnet = cm.getActiveNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                try {

                    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                        if (ni.isConnected())
                            haveConnectedWifi = true;
                    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                        if (ni.isConnected())
                            haveConnectedMobile = true;
                    if (informationabtnet.isAvailable()
                            && informationabtnet.isConnected())
                        connectionavailable = true;

                } catch (Exception e) {
                    // TODO: handle exception
                    System.out.println("Inside utils catch clause , exception is"
                            + e.toString());
                    e.printStackTrace();

                }
            }
            return haveConnectedWifi || haveConnectedMobile;
        }

Try this 尝试这个

//call web service
    ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);
    boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
    boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
    //check Internet connection
    if(internet||wifi)
    {
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show(); 
    }else{
                    Toast.makeText(this, "Not Connected", Toast.LENGTH_SHORT).show(); 
            }       

Also add following permissions to your Manifest file 同时向清单文件添加以下权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Try this one.        
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        boolean isActive=activeNetworkInfo != null && activeNetworkInfo.isConnected();
               if(isActive)
                 {
               System.out.print("Connection Establied");
                  }
                else{
                    System.out.print("Connection not Establied");
                     }

Try this 尝试这个

public class ConnectionDetector {
private Context _context;

public ConnectionDetector(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 in activity file 并在活动文件中

     ConnectionDetector cd= new ConnectionDetector(context);

   boolean  isInternetPresent = cd.isConnectingToInternet();

it will return true if internet is present 如果存在互联网,它将返回true

I think in your case this link may help you 我认为对于您而言,此链接可能会为您提供帮助

How can I receive a notification when the device loses network connectivity? 设备断开网络连接后如何接收通知?

The best way to check internet connection is to send a request and see whether you are getting back anything. 检查Internet连接的最佳方法是发送请求,然后查看您是否找回了任何东西。

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

相关问题 如何确定哪个网络适配器连接到Internet - How to determine which network adapter is connected to the internet 如何检查用户是否已连接到互联网wp7? - How to check if the user is connected to the internet wp7 ? UWP-如何检查是否连接到Wifi网络 - UWP-How to check if connected to a Wifi Network 如何检查PC是否通过路由器/交换机连接到互联网? - How to check if PC is connected to internet via router / switch? 如何判断是否连接到互联网 - How to tell if connected to internet 如何确定网络接口是否连接到Internet(即计算机是否在线) - How to determine if network interface is connected to the Internet (i. e. the computer is online) 检查Xamarin表单中的Internet连接是否已连接 - check internet connection is Connected or not in Xamarin Forms 如何判断手机是通过wifi连接的,还是可以通过C#访问移动互联网的? - How can I tell if a phone is connected by wifi or has access to mobile internet via C#? 没有 C# 中的 IP 地址和 Ping 方法,如何检查 PC 是否与 Internet 或 Intranet 连接? - How to check PC is connected with Internet or Intranet without IP address and Ping method in C#? ShareLinkTask,检查用户是否已连接到网络 - ShareLinkTask, check if a user has connected to a network
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM