How do I return a boolean from AsyncTask?

后端 未结 3 1992
闹比i
闹比i 2020-11-22 07:20

I have some EditTexts that a user enters an ftp address, username, password, port anda testConnection button. If a connection is successfully estabished it returns a boolean

3条回答
  •  既然无缘
    2020-11-22 07:43

    public interface MyInterface {
        public void myMethod(boolean result);
    }
    
    public class AsyncConnectTask extends AsyncTask {
    
        private MyInterface mListener;
    
    
        public AsyncConnectTask(Context context, String address, String user,
            String pass, int port, MyInterface mListener) {
            mContext = context;
            _address = address;
            _user = user;
            _pass = pass;
            _port = port;
            this.mListener  = mListener;
        }
    
        @Override
        protected Boolean doInBackground(Void... params) {
            ....
            return result;
       }
    
    
        @Override
        protected void onPostExecute(Boolean result) {
            if (mListener != null) 
                mListener.myMethod(result);
        }
    }
    
    AsyncConnectTask task = new AsyncConnectTask(SiteManager.this,
                            _address, _username, _password, _port,  new MyInterface() {
        @Override
        public void myMethod(boolean result) {
            if (result == true) {
                Toast.makeText(SiteManager.this, "Connection Succesful",
                Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(SiteManager.this, "Connection Failed:" + status, Toast.LENGTH_LONG).show();
            } 
        }
    });
    
    task.execute();
    

    If you call myMethod from onPostExecute the code inside it will run on the UI Thread. Otherwise you need to post a Runnable through a Handler

提交回复
热议问题