在后台线程中检查Android的Internet连接

时间:2016-01-11 00:45:34

标签: android multithreading

我正在尝试检查是否存在活动的互联网连接,并且在搜索之后,我找到了一个由Levit回答的工作代码:

https://stackoverflow.com/a/27312494/2920212

这似乎工作得很好,除非有时候,它会导致应用程序被冻结的延迟。我知道它,因为isOnline函数不在后台线程中运行。我已搜索但无法正确实现后台线程。请在下面找到代码:

    public boolean isOnline() {

    Runtime runtime = Runtime.getRuntime();
    try {

        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

以下是我尝试的内容:

    private void ChecOnline() {
    class CheckURL extends AsyncTask<Void, Void, Boolean> {


        @Override
        protected Boolean doInBackground(Void... params) {
            return isOnline();

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            String myresult = Boolean.toString(result);
            Toast.makeText(getApplicationContext(), myresult, Toast.LENGTH_LONG).show();
        }
    }
    CheckURL ucc = new CheckURL();
    ucc.execute();

ChecOnline()时没有任何反应;被称为。

1 个答案:

答案 0 :(得分:1)

使用AsyncTask

尝试
private class CheckOnlineStatus extends AsyncTask<Void, Integer, Boolean> {


    @Override
    protected Boolean doInBackground(Void... params) {
        //This is a background thread, when it finishes executing will return the result from your function.
        Boolean isOnline = isOnline();
        return isOnline;
    }

    protected void onPostExecute(Boolean result) {
    //Here you will receive your result from doInBackground
    //This is on the UI Thread
    }
}

然后你会打电话给

new CheckOnlineStatus().execute();

执行你的代码