Show Dialog everywhere if I don't know the current context? - android

I have to show a Dialog in the foreground activity as a result of a background http operation.
When the dialog has to come up it could be everywhere, the context can be changed, for example I have started a new Activity.
If I use the applicationContext to show the dialog I get:
05-04 17:32:32.560: E/AndroidRuntime(3663):
android.view.WindowManager$BadTokenException: Unable to add window --
token null is not for an application
so... How can I achieve my aim?
any suggestions?

Whenever/wherever you create the dialog you would be in an activity right? Why not just use that activity as the context?
In my own code, I create a helper class that creates a dialog for me. Into that helper class, I pass in the current activity, title and message. It constructs the dialog and returns an AlertDialog object which I can manage.
You could try that, but you would still need to know the context/activity where you want your dialog to display.

You need a way to notify your foreground Activity that the operation is complete, you can do this by registering a listener, since you have not posted any code, I will make assumptions.
There are two ways you can notify a foreground Activity that I know of, the first way is using broadcast intents, there is a question here relating to them Android BroadcastReceiver within Activity. You can fire of a broadcast intent from your background operation and register your activity as a receiver.
See here http://developer.android.com/reference/android/content/Context.html#sendOrderedBroadcast%28android.content.Intent,%20java.lang.String,%20android.content.BroadcastReceiver,%20android.os.Handler,%20int,%20java.lang.String,%20android.os.Bundle%29 and here
http://developer.android.com/reference/android/content/BroadcastReceiver.html
The second way is to register a listener with your class that performs the background operation, for instance (pseudo code)
#Override
protected void onResume() {
BackgroundOperator.registerListener(this);
}
#Override
protected void onPause() {
BackgroundOperator.unregisterListener(this);
}
public void onOperationComplete(...) {
// TODO: Show your dialog here
}
Where your listener could be something like this (which your Activity could implement):
interface BackgroundOperatorListener {
void onOperationComplete(...);
}
The idea here is your foreground activity will be the current registered listener, so it will be the recipient of the onOperationComplete(...) callback, and you can then show your dialog, the ... could be any number of arguments to pass to your activity when the operation is complete.

I think what you need is get the top activity of the task(current showing activity), then use it to show dialog.
so see this thread :How to get any identifier of the topmost activity?
Edit: Showing a dialog from background is not a good user experience, you can send notification or just make a long time toast.

In my opinion the best way is creating one new activity and using it like a dialog.
The steps:
Create new activity , for example (to being original) MainActivy.
Fill the activity_main.xml asociated as you need.
In the your AndroidManifest.xml re-write this lines.
<activity
android:theme="#style/AppTheme.Dialog"
android:name="com.myapp.original.example"
android:label="#string/timy_titlle" >
Call your MainActivity, now converted to Dialog, from others activies using the Intent class.
If you are using Action Bar Compact you can follow this others steps.

Related

how to implement popup window without any actions performed in android?

I want to show up pop up window after an activity has been launched. It is just like after a few seconds delay pop up should come. How can I implement that?Any ideas or examples?? If so I will be helpful ..Thanks in advance.
Many ways to do so.
If you have a list of Activities where you want to show the POP-up, you can uses two ways:
Create a service which actively checks for the foreground [Top most activities] in the stack and if the activity on which you want to show the pop-up, just send the broadcast to show the pop-up.
Create a Class which extends a Asynctask class, which waits for Xsecs in doinbackground and shows a pop-up over onpostexecute, Just call the execute of the Asynctask class while oncreate ends if you want to show only one time.
Asynctask class will be the best to use in such scenario. By this you can re-use this asynctask class every where in the project.
new Handler().postDelayed(new Runnable(){ #Override
public void run() {
// This method will be executed once the timer is over
//call your toast here.
//TIME_OUT is no of milliseconds you want to wait before Toast is popped.
} },TIME_OUT);
Hope this helps.

Launching dialog activity from services caused 'MainActivity' to also launch

I am designing an app that is used for emergency alerts. The alerts come from a server and a connection to that server is maintained in service.
If the service receives an emergency request from the server it checks to see if a specific activity is open. If it is it lets it know an emergency has been triggered and the activity launches a dialog activity with some options. It then handles results from this new dialog activity.
However, if the service notes that the activity is NOT open I want it to launch the dialog anyway. I know that this isn't good practise but because of the importance of this emergency I don't want to rely on Notifications (which are already in use if the activity is closed to let the user know that the app is still listening for emergencies).
What currently happens is that the below code is executed in the service and the dialog launches. However, the 'main' activity (the only other activity in the app) also opens behind the dialog. What I really want to happen is that either...
1) The service launches the main activity which then opens the dialog so that I can easily capture the results.
2) The service launches only the dialog activity and I use a broadcast receiver to capture results from this activity.
1 would use the mechanics that already exist for capturing results from an activity. However I don't like the idea of chaining the activities together in this way.
2 means I can ignore the main activity all together (because I don't really need it in this instance) but seems more of a get around.
What I am really asking is two things. What is best practise given my circumstances and how do i achieve number 2? Here is the launch code in my service. Notification in this code is referring to the dialog activity that will open.
if (MainActivity.isActivityInUI) {
//Dealt with by activity
sendMessageAlert(message);
} else {
//Launch dialog directly from service
Intent notification = new Intent(this,
EmergencyNotificationActivity.class);
Bundle args = new Bundle();
args.putString(MobileMessage.EXTRA_LOCATION_NAME,
message.locationName);
args.putString(MobileMessage.EXTRA_ID,
String.valueOf(message.id));
args.putDouble(MobileMessage.EXTRA_LATITUDE,
Double.valueOf(message.latitude));
args.putDouble(MobileMessage.EXTRA_LONGITUDE,
Double.valueOf(message.longitude));
//and the flag to let the notification know this is from a service...
args.putBoolean(EXTRA_FROM_SERVICE, true);
notification.putExtras(args);
//add flag because this is being called from outside of an activity
notification.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |ActivityInfo.LAUNCH_SINGLE_INSTANCE);
startActivity(notification);
I think instead of trying to show a dialog without visibly showing an Activity, you should consider launching an Activity that is themed like a Dialog. Just apply the following theme: http://developer.android.com/reference/android/R.style.html#Theme_Dialog (or similar themes) to your EmergencyNotificationActivity. You probably would have to tweak your class to behave like a dialog instead of launching one (which I am assuming is what you're doing currently).
This method would also allow you to not have to check if an Activity already exists.

Service displays an Allow/Deny AlertDialog through an Activity. How to get user's choice back in service?

I have a background service running that needs to display an Allow/Deny AlertDialog to the user and get his choice.
Roughly, this what I want. In my service, I have a code like this:
void someMethod()
{
boolean allow = showAllowDenyBox();
//Some operations based on the value of allow
}
I want to know how to implement the method showAllowDenyBox(). From this thread, I understand that I have to create an Activity and show the AlertDialog in that Activity. However, once the user selects Allow or Deny, how will I report that choice back to the service? Any help on this would be greatly appreciated.
In short, I want an AlertDialog to be spawned from inside a service and that must be synchronous.
You'll have to use the startActivityForResult method to implement this functionality. FOr more information on returning a result check out this SO post.
Basically using this method you inform the Android system that you want to get a result back from the activity you have passed to this method. Setting that result is explained very well in the above post. Do check it out.

Android Application, Activities, and UI Thread

I'm working on an Android project that consists of several different Activities all associated with the same Application. We have some common tasks coded in the Application so that we don't have to duplicate them, and one of these tasks is regularly verifying a TCP connection to a dedicated server -- a heartbeat, I suppose.
If it's detected that the connection to the server is lost, I need to notify the user and I'd like to do this in a way that doesn't require me to check all the possible activities to see which is currently "on top".
Is there a way to call runOnUiThread() on whatever activity may be on the UI thread without knowing it explicitly??
Thanks,
R.
Regularly verifying a TCP connection
Sounds like this should be implemented using a service..
If the alert is very simple, and has minimal importance, I would suggest using a Toast.
If the alert is crucial, but it doesn't require the user's immediate attention, use a Notification.
If the alert demands immediate user attention, you should use a Dialog. You won't be able to start a dialog directly from a service or broadcast receiver because they don't have a window associated with them, but you can use an intent to start an activity on a new task. You can style the activity to be whatever you want. It could even look like a dialog box (or show a dialog box when it's started). Starting the activity in a new task will make sure the user can navigate back to whatever they're doing.
You can notify your Activities by sending Intent and registering BroadcastReceiver in each Activity you want to be notified.
service or application can be your context:
Intent i = new Intent("MY_ACTION_FROM_SERVICE_STRING");
context.sendBroadcast(i);
activity:
public class MyActivity extends Activity {
private ActivityBroadcastReceiver recvr;
public void onReceiveCommand() {
//do something
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
recvr = new ActivityBroadcastReceiver(this);
this.registerReceiver(recvr,
new IntentFilter("MY_ACTION_FROM_SERVICE_STRING"));
}
}
receiver:
public class ActivityBroadcastReceiver extends BroadcastReceiver {
private MyActivity target;
public ActivityBroadcastReceiver(MyActivity target) {
this.target = target;
}
#Override
public void onReceive(Context context, Intent intent) {
target.onReceiveCommand();
}
}
One of the simple way (which I've adopted for my project too) is to create a base Activity class (preferably Abstracted) and then make your normal activity classes to extend it. By this, you may put a general piece of code in the abstracted class which may help you to detect currently visible activity.
Moreover, you may set a BroadcastReceiver in your base activity class which will always be ready to listen broadcasts regardless of setting it individually in your child activities and then set it to listen for broadcasts sent from your tcp thinggy.
Do not do any trickery. Implement Observer pattern, so any activity would register its listener in onResume() and unregister in onPause() and whatever will happend your Application object code needs just to tell about that to registered listeners, no matter what Activity they are in

Open a PopUpWindow from an AppWidget

As it doesn't appear to be possible to put an EditText in an AppWidget, I would like to open a PopUpWindow with an EditText when I click on it.
I know how to open an Activity from an AppWidget and I also know how open a PopUpWindow from an Activity. I don't, however, know how to open a PopUpWindow from an AppWidget. I've looked into many classes in the javadoc (Intent, RemoteViews, PendingIntent, etc.), but I can't find how to start this PopUpWindow. Any help would be appreciated.
You know that AppWidgetProvider is a BroadcastReceiver.Android Doc says:
A BroadcastReceiver object is only valid for the duration of the call
to onReceive(Context, Intent). Once your code returns from this
function, the system considers the object to be finished and no longer
active.
This has important repercussions to what you can do in an
onReceive(Context, Intent) implementation: anything that requires
asynchronous operation is not available, because you will need to
return from the function to handle the asynchronous operation, but at
that point the BroadcastReceiver is no longer active and thus the
system is free to kill its process before the asynchronous operation
completes.
In particular, you may not show a dialog or bind to a service from
within a BroadcastReceiver. For the former, you should instead use the
NotificationManager API. For the latter, you can use
Context.startService() to send a command to the service.
It seems you have three ways:
Use a service to show popup(see How to display alert diaolog(popup) from backgroung running service?)
Use notification manager(see AlarmManager never calling onRecieve in AlarmReceiver/BroadcastReceiver).
Create an activity whit dialog theme(so it looks like a popup) and display it when user click your AppWidget.
You could have the appWidget open an activity which then shows a dialog fragment, or make the activity look like a dialog using a dialog style.

Categories

Resources