【问题标题】:how to check net connection in android phone [duplicate]如何检查Android手机中的网络连接[重复]
【发布时间】:2011-12-29 07:31:02
【问题描述】:

可能重复:
Android - detect whether there is an Internet connection available
How to check network connection enable or disable in WIFI and 3G(data plan) in mobile?

在我的单元格中,当我运行我的应用程序时,该应用程序崩溃了,因为网络连接不存在。所以如何给出连接不存在的消息。或在你的妻子身上

请帮帮我

谢谢

【问题讨论】:

  • 网上有很多相同的例子:Android check network connection

标签: android wifi


【解决方案1】:

见下面的代码。

ConnectivityManager conMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    // ARE WE CONNECTED TO THE NET
    if (conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable()
            && conMgr.getActiveNetworkInfo().isConnected()) {
        return true;

        // internet connection is wroking
    } else {
        return false;
        // internet connection is not wroking
    }

【讨论】:

    【解决方案2】:

    在你的活动中使用这个方法,当你想知道网络是否可用时调用它。

    public boolean isInternetOn(Context ctx) {
        this.mContext = ctx;
        ConnectivityManager Connect_Manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        State connected = NetworkInfo.State.CONNECTED;
        State connecting = NetworkInfo.State.CONNECTING;
        State disconnected = NetworkInfo.State.DISCONNECTED;
    
        State info0 = Connect_Manager.getNetworkInfo(0).getState();
        State info1 = Connect_Manager.getNetworkInfo(1).getState();
    
        // ARE WE CONNECTED TO THE NET
        if (info0 == connected || info0 == connecting || info1 == connecting
                || info1 == connected) {
    
            // MESSAGE TO SCREEN FOR TESTING (IF REQ)
            // Toast.makeText(this, connectionType + " connected",
            // Toast.LENGTH_SHORT).show();
            Log.d("Internet", "Connected");
            return true;
        } else if (info0 == disconnected || info1 == disconnected) {
            Log.d("Internet", "DisConnected");
            // System.out.println("Not Connected");
            return false;
        }
        return false;
    }
    

    现在检查互联网连接,

    if (isInternetOn(this))
         {
    
            //Do stuff          
          }
    else
           {
    
               //show alert
            }
    

    【讨论】:

      猜你喜欢
      • 2013-04-06
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 2010-10-05
      • 1970-01-01
      相关资源
      最近更新 更多