Certainly! Below is the example code that demonstrates how to put an AsyncTask in a separate class and implement a callback in Java.

1. Create the AsyncTaskCallback interface:

             java
public interface AsyncTaskCallback {
    void onTaskComplete(String result);
}

             

2. Create the MyAsyncTask class that extends AsyncTask:

             java
public class MyAsyncTask extends AsyncTask<Void, Void, String> {
    private AsyncTaskCallback callback;

    public MyAsyncTask(AsyncTaskCallback callback) {
        this.callback = callback;
    }

    @Override
    protected String doInBackground(Void... voids) {
        // Simulate a background task
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Task completed!";
    }

    @Override
    protected void onPostExecute(String result) {
        callback.onTaskComplete(result);
    }
}

             

3. Implement the AsyncTaskCallback in your activity:

             java
public class MainActivity extends AppCompatActivity implements AsyncTaskCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyAsyncTask myAsyncTask = new MyAsyncTask(this);
        myAsyncTask.execute();
    }

    @Override
    public void onTaskComplete(String result) {
        Log.d("AsyncTask", "Task result: " + result);
    }
}

             

4. Run your application to see the output in logcat:

             
Task result: Task completed!

             

Explanation:

– We first create an interface named AsyncTaskCallback with a method `onTaskComplete()` that will be implemented by the activity.

– Then, we create a separate class MyAsyncTask that extends AsyncTask and takes an AsyncTaskCallback instance as a parameter in the constructor.

– Inside the doInBackground() method of MyAsyncTask, we simulate a background task by sleeping the thread for 3 seconds and then return a string result.

– In the onPostExecute() method, we call the onTaskComplete() method of the callback interface with the result obtained from the background task.

– The MainActivity implements AsyncTaskCallback and overrides the onTaskComplete() method to handle the result of the AsyncTask.

– In the MainActivity's onCreate() method, we create an instance of MyAsyncTask and execute it. The result of the AsyncTask will be received in the onTaskComplete() method.

– When the AsyncTask completes its task, the onTaskComplete() method is called, and the result is logged using Log.d().

This way, you can separate the AsyncTask logic into its own class and provide a callback mechanism to communicate the result back to the calling activity.

Was this article helpful?
YesNo

Similar Posts