java – Passing a reference to an Activity to an AsyncTask, why is it bad and how could it be otherwise

Question:

All that is described below is how I used the interface to get the result from AsynckTack to the main thread using CallBack . Why was I told that it's bad that I passed the link to the activity in AsyncTask ? And what better way to do it?

Here in the MainActivity class I call such a method and, as you can see, I pass a link to the activity to AsyncTack

private void UploadData() {
        String url = "https://qwerty.ru" ;
        AsyncUploadingData asyncUploadingData = new 
        AsyncUploadingData(this);
        asyncUploadingData.execute(url);
    }
}

The interface is embedded in AsyncTack

interface AsyncResult {
        void getResult(String answer);
    }

Declared private AsyncResult mCallback;

And in the constructor I accept a link to the activity. And I implicitly bring to the interface (is it correct to say so?)

 AsyncUploadingData(AsyncResult mCallback) {
        this.mCallback = mCallback;
    }

And at a certain moment I call the interface method, and the interface is connected to MainActivity

 mCallback.getResult(answer);

Answer:

Why was I told that it's bad that I passed the link to the activity in AsyncTask ?

Storing a reference to an activity in AsyncTask fraught with the fact that if the transferred activity is destroyed while the asynctask is running:

a) A memory leak will occur, since the GC will not be able to remove the activity from memory, since a link will be stored on it (in the case of a strong reference);

b) Calling the methods of an activity will, at best, lead to nothing, and at worst, errors will occur.

The first problem is solved by storing the activity as a weak reference, but the second problem remains.

And what better way to do it?

There are a large number of ways to solve this problem.

For example, you can use loaders or retain fragments (loaders save their state just with the help of retain fragments).

Various libraries can be used, such as Chronos .

If you are using MVP, then you can use the Moxy library, which, in particular, solves your problem.

Scroll to Top