簡體   English   中英

如何檢查Wifi是否已連接,但Android中無法訪問Internet

[英]How to check Wifi is connected, but no Internet access in Android

我想知道為什么wifi連接但Android沒有互聯網接入。 我怎么檢查它? 我的代碼是:

ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo nf=cn.getActiveNetworkInfo();

 if(nf != null && nf.isConnected() )
         {
            Flag2=false;
            Log.e("network--------", "1--------------");

            if (cn.getActiveNetworkInfo().isConnectedOrConnecting())
            {Log.e("network--------", "11111111111111--------------");
             }
            else
            {Log.e("network--------", "2222222222222--------------");
            }
        }

 else 
         {
            Log.e("network--------", "2--------------");
 }

你可以嘗試這樣的事情:

public void checkOnlineState() {
    ConnectivityManager CManager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
        if (InetAddress.getByName("www.xy.com").isReachable(timeout))
        {  
         // host reachable  
        }
         else
         {    
         // host not reachable  
         }  
    }
    return;
}

不要忘記訪問權限

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

希望它會工作:)

用這個 :

public static boolean isInternetOn(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        // test for connection
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            Log.v(TAG, "Internet is working");
            // txt_status.setText("Internet is working");
            return true;
        } else {
            // txt_status.setText("Internet Connection Not Present");
            Log.v(TAG, "Internet Connection Not Present");
            return false;
        }
    }

希望這可以幫助。

除了你現在正在做的事情,你可以使用BroadcastReceiver為你的應用程序通過注冊<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> intent來獲得連接變化時的通知。

有關詳細說明,請查看docs: BroadcastReceiverConnectivity Monitoring

我希望它會有所幫助!

ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            return true;
        }
        return false;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM