Should I use the WeakReference <Context> or Application Context in my AsyncTask?

I have a bit of a dilemma, and I hope you guys can help me.

As you can see, I have AsyncTask, in which I have code for saving objects Bitmapas a .jpg file in the gallery. As AsyncTaskI also use Context, but as I understand that the use of context Activityin this inner class can cause a memory leak, so I changed it to WeakReference<Context> weakContext;, so the garbage collector can collect it.

But using the context Applicationthat I get from the passed Viewfrom the constructor, I have to archive the same effect as the reference to the weak context

So is it better to use than in this case?

public class ViewToBitmap {

private View view;
private WeakReference<Context> weakContext;

public ViewToBitmap(@NonNull View view) {
    this.view = view;
}

 // This?
private WeakReference<Context> getContext() {
    weakContext = new WeakReference<>(view.getContext());
    return weakContext;
}

 // Or This?
private Context getContext() {
    return view.getContext().getApplicationContext();
}

private class AsyncSaveBitmap 
                extends AsyncTask<Void, Void, Void> 
                implements MediaScannerConnection.OnScanCompletedListener {

    @Override
    protected Void doInBackground(Void... params) {
      //TODO: Save bitmaps to gallery
      //CONTEXT IS USED HERE
       getContext().get()
       return null;
    }
}
+4
1

View Context, , "" Context ViewToBitmap, View.

, AsyncSaveBitmap static, ViewToBitmap.

, AsyncSaveBitmap, Activity, GC Activity.

, : .

, Context, Activity, View ..

Observer Publish-Subscribe - " " (, onStop()), .

EDIT:

, Context Context, ( , ​​ Singleton ):

// Use this approach if clients will use your library as Singleton
private static Context sAppContext;

public static void init(Context context) {
    sAppContext = context.getApplicationContext();
}

// Use this approach if clients will instantiate your library object on each use
private final Context mAppContext;

public MyLibraryEntryClass(Context context) {
    mAppContext = context.getApplicationContext();
}
+3

Source: https://habr.com/ru/post/1667276/


All Articles