2

What would be the best way to display a dialog whenever my app receives some sort of notification from the android platform? e.g., orientation or the device language gets changed, etc..

The challenge for me is I don't know how to get the current activity context, so it's hard to use a AlertDialog.

Also, I want to show this dialog only if the app is running in the foreground, so my 2nd question is if there a reliably way to detect if the app is running in the foreground?

Thanks!

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Green Ho
  • 881
  • 3
  • 14
  • 27
  • 1
    **I don't know how to get the current activity context** - `Activity` extends `Context` therefore any `Activity` **IS** a `Context` and you can simply use `this` when you need to pass a `Context` to anything (including when creating an `AlertDialog`). – Squonk Jun 22 '12 at 23:58
  • I know every activity is a context, but the other way is not true, so I don't know which activity is currently in the foreground, then when I create the AlertDialog, I don't know which activity I should pass in. – Green Ho Jun 23 '12 at 00:06
  • An Observer/Listener can do such stuff, every active Activity just registers it's own [Callback Method](http://stackoverflow.com/questions/11156496/is-there-a-sendtoactivity-method/11156863#11156863) in your app. edit: [better explanation of the concept](http://stackoverflow.com/questions/443708/callback-functions-in-java) – trichner Jun 23 '12 at 00:08
  • 2
    If you really want to get the current Activity, you can [use this solution](http://stackoverflow.com/a/4753333/119114). It, of course, might not be *yours*. – Nate Jun 23 '12 at 00:25

1 Answers1

1

You should use a BroadCastReceiver. Mark Murphy describes how you can do this in the post below:

How can I display a dialog from an Android broadcast receiver?

Community
  • 1
  • 1
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
  • Thanks, but my app has many activities which may or may not be derived from the same base activity class where I suppose the broadcastReceiver should be used per Mark's example, so it could be a bit complex to make sure each activity can display the dialog or push the notification properly. – Green Ho Jun 23 '12 at 01:23
  • Perhaps you could create an `abstract class BaseActivity extends Activity` and have all of the relevant activitys in your project `extend BaseActivity`? or something like that? That way you can implement the notification/dialog functionalities in the `BaseActivity` class and have activitys inherit this behavior? – Alex Lockwood Jun 23 '12 at 01:31
  • yeah, there's some reason behind that i can't have all activities extend the base activity, that's the hard part for me :-) – Green Ho Jun 23 '12 at 01:47