close

最近需要用到判斷網路是否有辦法連到特定網頁

有時候wifi是有連線的但是其實打開網頁是打不開的

這時候用ConnectivityManager其實還是只能判斷出網路是有連線的

所以就要用另一種方法ping來解決~~


 

下面這個fun就是用來判斷是否有連上yahoo

可以自行替換想要判斷的網頁

public boolean ping() {
    try {
        String ip = "tw.yahoo.com";//連線到yahoo,記得前面不需要https://
        Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);
        InputStream input = p.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(input));
        StringBuffer stringBuffer = new StringBuffer();
        String content = "";
        while ((content = in.readLine()) != null) {
            stringBuffer.append(content);
        }
        int status = p.waitFor();
        if (status == 0) {
            Log.d(TAG, "internet 成功");
            return true;
        } else {
            Log.d(TAG, "internet 失敗");
        }
    } catch (IOException e) {
        Log.d(TAG, "internet 失敗");
    } catch (InterruptedException e) {
        Log.d(TAG, "internet 失敗");
    } finally {
        
    }
    return false;
}

我會先去判斷網路到底有沒有連上線

如果有的話才會用上面的fun去判斷網路到底有沒有通

arrow
arrow
    文章標籤
    Android App JAVA
    全站熱搜

    小小工程師 發表在 痞客邦 留言(0) 人氣()