android - What is the best way of getting / using Context inside AsyncTask? -
i've defined separate thread extending asynctask
class. within class perform toasts , dialogs within asynctask's onpostexecute
, oncancelled
methods. toasts require application's context such need is:
toast.maketext(getapplicationcontext(),"some string",1);
the dialogs created using alertdialog.builder
requires context in constructor. right in thinking context should activity's context? i.e.
alertdialog.builder builder = new alertdialog.builder(getactivity());
where getactivity
user defined class returns current activity. if best way handle situation? creating class getactivity
or passing current activity's context asynctask's constructor?
i guess i'm trying understand use of context
- have noticed memory leaks can issue (don't understand yet) , how using getapplicationcontext()
best approach possible.
simply create asynctask inner class of activity, or pass context constructor of asynctask.
inner class: myactivity.java
public class myactivity extends activity { // other methods of activity here... private class mytask extends asynctask<void, void, void> { protected void doinbackground(void... param) { publishprogress(...); // 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(...); // call onprogressupdate(); } protected void onprogressupdate(void... prog) { toast.maketext(c, "text", 1000).show(); } }
furthermore, please not forget call .show() on dialog.
alertdialog.builder builder = new alertdialog.builder(getactivity()); builder.show();