2016-12-30 66 views
0
String url = "http://xyzcloud.com/xyz/xyz.php"; 

沒有互聯網接入這個網址我試圖從雲中的數據,如果網絡連接,然後異步任務將執行 我寫了這個方法檢查羯羊互聯網連接與否,在這裏我的移動WLAN網絡時我試圖執行它給例外如何停止在互聯網連接的AsyncTask,但在Android的

public boolean checkOnlineState() 
    { 
     boolean val = false; 
     ConnectivityManager CManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo NInfo = CManager.getActiveNetworkInfo(); 
     if (NInfo != null && NInfo.isConnectedOrConnecting()) { 
      try { 
       if (InetAddress.getByName(url).isReachable(10000)) 
       { 
        // host reachable 
        val=true; 
        Log.e("checkOnlineState", "" + val); 
       } 
       else 
       { 
        // host not reachable 
        val = false; 
        Log.e("checkOnlineState", "" + val); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     return val; 
    } 
+0

這是例外,我得到 致命異常:主要 過程:com.xyz.xyz,PID:13405 android.os.NetworkOnMainThreadException 在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1288 ) \t在java.net.InetAddress.lookupHostByName(InetAddress.java:432) \t在java.net.InetAddress.getAllByNameImpl(InetAddress.java:253) \t在java.net.InetAddress.getByName(InetAddress.java: 306) – veeraprasad

+0

手柄插座超時而連接在catch塊 – Raghunandan

+0

超時增加兩個異常之後,它漚甕假 – veeraprasad

回答

0
import android.app.Service; 
import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 

public class ConnectionDetector { 

    private Context context; 

    public ConnectionDetector(Context context) { 

     this.context = context; 
    } 

    public boolean isConnected() { 

     ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Service.CONNECTIVITY_SERVICE); 

     if (connectivity != null) { 

      NetworkInfo info = connectivity.getActiveNetworkInfo(); 

      if (info != null) { 

       if (info.getState() == NetworkInfo.State.CONNECTED) { 

        return true; 
       } 
      } 
     } 

     return false; 
    } 
} 

再比如說,你可以利用它connetecd:

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     ConnectionDetector cd = new ConnectionDetector(this); 

     if (cd.isConnected()) { 
      // do something 
     } else { 
      //do something 
     } 

     setContentView(R.layout.activity_main); 
    } 
} 

我用這個方法在我的應用程序(這需要互聯網連接),並沒有遇到任何問題呢。

+0

妻子已連接,但在這種情況下無法上網這是給這個異常org.apache.http.conn.HttpHostConnectException:連接到http://xyzcloud.com拒絕 – veeraprasad

+0

你有沒有加入到permision清單文件:<使用許可權機器人:名字=「android.permission.ACCESS_NETWORK_STATE」 /> –

+0

是的,我已經加入 – veeraprasad

相關問題