What is the best way to get / use context inside AsyncTask?

I defined a separate thread by extending the AsyncTask class. In this class, I do some toasts and dialogs in the AsyncTask onPostExecute and onCancelled . Toasts require an application context, so all I need is:

 Toast.makeText(getApplicationContext(),"Some String",1); 

Dialogs are created using AlertDialog.Builder , which also requires context in its constructor. Do I believe that this context should be an activity context? i.e.

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 

where getActivity can be a user-defined class that returns the current activity. If so, what is the best way to handle this situation? Creating a class of type getActivity or passing the current activity context to the AsyncTask constructor?

I think I'm trying to understand the use of Context . I noticed that a memory leak can be a problem (in fact, this is not yet clear), and how using getApplicationContext() is the best approach where possible.

+6
source share
1 answer

Just create AsyncTask as the inner class of your activity, or pass the context to the AsyncTask constructor.

Inner Class: MyActivity.java

 public class MyActivity extends Activity { // your other methods of the activity here... private class MyTask extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... param) { publishProgress(...); // this will call onProgressUpdate(); } protected Void onProgressUpdate(Void... prog) { Toast.makeText(getActivity(), "text", 1000).show(); } } } 

Constructor: MyTask.java

 public class MyTask extends AsyncTask<Void, Void, Void> { Context c; public MyTask(Context c) { this.c = c; } protected Void doInBackground(Void... param) { publishProgress(...); // this will call onProgressUpdate(); } protected Void onProgressUpdate(Void... prog) { Toast.makeText(c, "text", 1000).show(); } } 

Also, be sure to call .show () in the dialog box .

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.show(); 
+12
source

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


All Articles