Home >Java >javaTutorial >How Can I Return a Boolean Value from an Android AsyncTask?
Returning a Boolean from AsyncTask
In Android development, it may be necessary to return a boolean value from an asynchronous task performed by AsyncTask. This is useful in situations where you need to determine the success or failure of a specific operation.
To return a boolean from AsyncTask, you can implement a callback interface. Here's how to do it:
public interface MyInterface { public void myMethod(boolean result); }
public class AsyncConnectTask extends AsyncTask<Void, Void, Boolean> { 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; } // ... (Rest of the AsyncTask code) }
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();
By following these steps, you can effectively return a boolean value from an AsyncTask and handle the result accordingly.
The above is the detailed content of How Can I Return a Boolean Value from an Android AsyncTask?. For more information, please follow other related articles on the PHP Chinese website!