Android:如何从AsyncTask获取布尔结果?

时间:2018-09-26 08:56:49

标签: android android-asynctask connection

我想检查我的应用程序中的Internet连接。我找到了代码,但由于我是一个真正的初学者,所以我不知道如何使用。

我的代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
            //I want something like this.
            if(InternetCheck==true){
                Toast("You are connected to internet")
            }
            else{
            Toast("Connection Failed")
            }

    }

 static class InternetCheck extends AsyncTask<Void,Void,Boolean> {

        private Consumer mConsumer;
        public  interface Consumer { void accept(Boolean internet); }

        public  InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); }

        @Override protected Boolean doInBackground(Void... voids) { try {
            Socket sock = new Socket();
            sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
            sock.close();
            return true;
        } catch (IOException e) { return false; } }

        @Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); }
    }

但是我不知道如何从AsyncTask获得布尔结果。请教我。

2 个答案:

答案 0 :(得分:2)

new InternetCheck(new InternetCheck.Consumer() {
    @Override
    public void accept(Boolean connected) {
        if (connected) {
            Log.d("TAG", "Internet is connected");
        } else {
            Log.d("TAG", "Internet is not connected");
        }     
    }
}).execute();

答案 1 :(得分:0)

您可以使用AsyncTaskget()获得结果:

@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
                Boolean result = new InternetCheck().execute().get();
                if (result == true) {
                    Toast.makeText(this, "You are connected to internet", Toast.LENGTH_LONG).show();
                } else { 
                    Toast.makeText(this, "Connection Failed", Toast.LENGTH_LONG).show();
                }
        }

或者您可以在AsyncTask的{​​{1}}中检查布尔结果:

onPostExecute()