2

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);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jason Rogers
  • 19,194
  • 27
  • 79
  • 112

3 Answers3

2

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();

Chris
  • 940
  • 10
  • 24
  • 1
    That will work as long as you have access to the Activity, ie you have passed the activity, or are running in an object which has access to an enclosing activity – jqpubliq Jul 13 '11 at 00:08
  • I've found that the above Toast code will work correctly from a service, by it does fail if one tries to open a dialog box. I wouldn't be surprised to discover that I'm missing a key concept, though. :) – Chris Jul 14 '11 at 00:05
1

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

jqpubliq
  • 11,874
  • 2
  • 34
  • 26
  • Keeping a static reference to a `Context` is not necessarily a memory leak. If it’s the application’s `Context`, this is not a leak, and if it’s an activity’s `Context`, you just have to be careful and remove it as soon as the Activity is destroyed. – Guillaume Brunerie Jul 13 '11 at 00:07
0

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

Community
  • 1
  • 1
Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32