Home >Java >javaTutorial >How Can I Return a Boolean Result from an AsyncTask in Android?
An asynchronous task (AsyncTask) is often employed for performing time-consuming operations background processing. However, when needing to pass back a boolean value indicating a successful connection, how can this be achieved?
To return a boolean from AsyncTask, you can leverage an interface to define a method for receiving the result. Here's how:
public interface MyInterface { public void myMethod(boolean result); }
Inside the AsyncConnectTask, inject the interface as an argument to the constructor.
public AsyncConnectTask(Context context, String address, String user, String pass, int port, MyInterface mListener) { mContext = context; ... this.mListener = mListener; }
When initializing the task, provide an implementation of the interface to handle the boolean 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(); } } });
Initiate the task as usual:
task.execute();
This approach ensures the result, whether a successful connection or failure, is communicated through the interface and runs on the UI thread within the onPostExecute method.
The above is the detailed content of How Can I Return a Boolean Result from an AsyncTask in Android?. For more information, please follow other related articles on the PHP Chinese website!