Get application context to display graphical components
I've been wondering how to do this correctly for a while.
I want to display a Dialog or Toast (or anything graphic) from another place than my main thread.
But for that I need to pass a Context.
The bruteforce way is either the pass the context along all the time or to create a static variable in which I store the context.
Those work but are not the way to go so can somebody tell me the correct way to complete this:
ProgressDialog.show([...], "",[...].getResources().getString( R.string.logoutProgressMessage), true);
What you're looking for is runOnUiThread. That should make things a lot easier. :)
For other classes in the main thread, try getApplicationContext. I've used that from other classes and services for Toasts. For example:
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Your timer has expired", Toast.LENGTH_LONG);
toast.show();
Making a Handler in your main thread and having your background threads use that to post to your UI thread is likely the most appropriate solution.
Really try Not to keep a static reference to your Context
as that is a big leak
You can use a static field to store the application’s Context
(obtained by the method getApplicationContext()
), this will not induce a memory leak.
You can find an example of code implementing this solution in this question
精彩评论