Android anonymous class Loaders security leaks?

In Android development, I learned that AsyncTask defined as a non-static nested class is not ideal because it can cause a memory leak when the activity that started the task dies before the task is finished processing.

So the solution is to use Loaders , whose lifecycle is independent of the lifecycle.

However, that's in a situation like this , where they defined an anonymous AsyncTaskLoader. It seems to me that this Loader has a link to its external activity.

(1) Doesn't it leak memory when the initial activity cannot be garbage collected?

In addition, the Loader onStartLoading () method contains a reference to the mLoadingIndicator external activity element.

(2) If onCreateLoader is only called the first time the application is launched, will this loader forever hook onto that first mLoadingIndicator activity, ignoring the view from the new activity? (For example, after changing the configuration)

+3


source to share


1 answer


However, how about a situation where she defined an anonymous AsyncTaskLoader. It seems to me that this Loader has a link to its external activity.

Yes, he has.

(1) Doesn't it leak memory when the initial activity cannot be garbage collected?

Yes Yes. If this one Loader

runs indefinitely and is longer than the encompassing one Activity

, it may interfere with the garbage collection of the context.

(2) If onCreateLoader is only called the first time the application is launched, will this loader forever hook onto that first mLoadingIndicator activity, ignoring the view from the new activity? (For example, after changing the configuration)



onCreateLoader

does not linger on the view mLoadingIndicator

, but calls only one of its methods. What really matters is that the object mLoadingIndicator

refers to the moment onCreateLoader

.

In fact, the bootloader is delayed in external activity. If a configuration change created a new loading indicator, and only then is called onCreateLoader

, the method will use the new view.

Example

An AsyncTaskLoader

can be referenced Activity

without causing memory leaks by wrapping it in WeakReference

.

public class MyAsyncTaskLoader extends AsyncTaskLoader<String> {

    private final WeakReference<Activity> mActivity;

    public MyAsyncTaskLoader(Activity activity) {
        super(activity);
        mActivity = new WeakReference<>(activity);
    }

    public doYourThing() {
        Activity activity = mActivity.get();

        // if activity is destroyed and garbage collected,
        // it will be null
        if (activity != null) {
            activity.getYourView().setWhatever();
        }
    }
}

      

+1


source







All Articles