AlertDialog.show silently ignored within a service - android

I have a service running a background thread. What I'd like to do is to
show an AlertDialog initiated from my background thread. I know that
this is not the recommended way of notifying the user and that it
interrupts the workflow (as they can pop-up in any application at any
time) but it's a suitable way for my use case.
There is a handler registered with the background thread and showing a
Toast notification withing the handler works fine. But after switching
to an AlertDialog nothing happens anymore. My showDialog logic is
silently ignored. No Dialog window appears, no log entry. It's a bit
strange as I'd expect at least a log entry saying that I'm doing
something wrong or whatever.
Are there any limitations for showing an AlertDialog initiated from a
service background thread? Some people seem to recommend a Dialog themed
Activity to get a similar behavior.
Any clarification or help making it work is greatly appreciated!
Yves

It is possible to open a dialog from a background thread. The trick is to start an activity which looks like a dialog:
<activity android:label="#string/app_name" android:name="YourDialog" android:theme="#android:style/Theme.Dialog"/>
Then, to start your activity:
Intent dialog = new Intent(this, YourDialog.class);
dialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialog);
Note that this is asyncrhonous and doesn't block. If you want to process the result, you'll have to use startService() and pass a custom activity to indicate a result.
Emmanuel

Are there any limitations for showing an AlertDialog initiated from a service background thread?
The limitation is: it's not possible, AFAIK. You have to show dialogs from the main application thread, not just some arbitrary thread on which you have a Handler.
Some people seem to recommend a Dialog themed Activity to get a similar behavior.
That would seem to be the most likely solution, AFAICT.

Another trick is to stay with the AlertDialog but with an additional window type TYPE_SYSTEM_ALERT:
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Are you sure?")
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
But don't forget to add this permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

Related

How to show dialog in activity from service?

I'm developing an app that downloads some data in service and show it via push-notifications, also user can read other data in activity. So could you explain me how can i make a dilalog that's show's to user when WIFI/3G is turned off and says something like this "For normally app working you should turn 3G/WIFI on". A problem is that i must implemet it by service callback, i.e. by this logic:
service start downloading data --> No internet --> Cheks if WiFi/3G is turned off --> Shows in any Activity a Dialog.
I know that i can make it by using a receiver, but how a can call a dialog in every activity? Or i don't need an activity, just a context in OnReceive method, right? Please give me any ideas.
Or i don't need an activity, just a context in OnReceive method, right?
No, that is incorrect. A Dialog needs an Activity. You could show a Toast from onReceive() using the Context that it has.
Or, as Junior was suggesting, you can create an Activity with a Dialog theme. To do this, you simply need to add the following line to the <activity> tag in your manifest.xml for the appropriate Activity
android:theme="#android:style/Theme.Dialog"
This is nice because it gives you all the functionality of an Activity while displaying as a Dialog so the user doesn't feel like they have "left" where they are.
Launch an activity (of your own) with a dialog theme.
Hope it helps!

Launching Dialog from Service

I want to launch a dialog from a service that hovers over whatever the user is currently looking at. The dialog gets launched like this: service gets trigger to open dialog > start transparent activity > transparent activity shows dialog.
My problem is when the user opens the app, launches into the main menu, and then presses HOME to leave. By pressing HOME, it leaves the main menu activity on pause, not destroyed, and when the service starts the dialog, the main menu gets shown underneath the transparent activity; causing the dialog to loose the affect of hovering over whatever the user is looking at.
How can make it so that the transparent activity gets opened independently of any other activities in the app? The only way to prevent this currently is to finish all the activities when they are paused; but this is impractical.
This is the last thing we want. :-)
1. Dialog boxes from Services
One of the best experiences in mobile devices, IMHO, and Android in particular, is that after decades, we got rid of system-wide, pesky alert dialogs. Finally, best practices [1, 2] for user interaction gave us a way to avoid the infamous disseminate use of MessageBox(hwnd, lpText, lpCaption, uType), competing for focus and for the attention of the poor user. See video parody above.
The reason it feels awkward to start a dialog from a Service is exactly because it is supposed to be a background task, without user interaction. By concept, you shouldn't be doing this. That's the reason why we see these tricks (transparent activities, what a silly thing) to cheat the design guidelines in the first place. They are bad, they disrupt the user experience, they steal focus and attention. They disrupt our work.
2. Use notifications instead
Whenever you want to notify a user of something from the background, when the user is somewhere else, you use a notification. It's the default pattern, and it doesn't bother the user.
Therefore, you should be sending notifications from your Service.
From there, if the user is interested, then he will touch the notification and you start your own activity, possibly resuming your activity, creating a new one, and then using a dialog requesting action to be performed, or whatever you want to do.
3. Finally, do NOT use FLAG_ACTIVITY_MULTIPLE_TASK
You should not, ever, use this flag unless you have carefully read and fully understood the documentation, and the implications of using that flag.
Do not use this flag unless you are implementing your own top-level application launcher.
(...)
Because the default system does not include graphical task management, you should not use this flag unless you provide some way for a user to return back to the tasks you have launched.
Really. In this case, just don't.
You may consider using alertDialog with TYPE_SYSTEM_ALERT instead of activity:
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Are you sure?")
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
Please note that you have to use the following permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Found this out myself, just add the Intent.FLAG_ACTIVITY_MULTIPLE_TASK flag to the launch Intent; of course in conjunction with the Intent.FLAG_ACTIVITY_NEW_TASK flag.

Android AlertDialog Box Not Showing

I've searched through Stackoverflow, looked at the examples in Android Developer, and some books and I'm just not getting it.
I'm trying to show an AlertDialog Box that interrupts the program flow. Most of the examples I've seen don't have code after the dialog box and I need my program to stop executing until the AlertDialog button is pressed. Seems as if the AlertDialog is created from another thread and I'm not sure how to retrieve that thread.
Program logic: If the parsing is bad the program will force close. I want to let the user know to restart the program and everything will work. (I'm dropping and recreating tables and they are repopulated when the program starts back up)
Here's some code:
if(database populated)
{
....code.....
if(parseok.contentEquals("Error"))
{
doForceClose();
}
displayDate = "Last: " + parseok; //I don't want the program to continue to here.
//Rest of code in the method. If I continue the program will Force Close
}
else
do something else
Here's the AlertDialog method:
private void doForceClose()
{
String themessage = "Because some of the parameters have changed in the yada yada";
AlertDialog.Builder ad = new AlertDialog.Builder (this);
ad.setTitle("Internal Error");
ad.setMessage(themessage);
ad.setPositiveButton("Sorry", new OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
finish();
return;
}
});
ad.create();
ad.show();
}
except ad doesn't show and the program continues to its force close.
Obviously I'm not getting something. Any ideas?
edit: I am in a Class that extends Activity
I'm trying to show an AlertDialog Box that interrupts the program flow.
That does not exist in Android and various other UI systems.
I need my program to stop executing until the AlertDialog button is pressed.
No, you don't. Event-driven programming has been in use for a couple of decades.
Program logic: If the parsing is bad the program will force close.
That's your code -- rewrite it to behave better.
I don't want the program to continue to here.
Then use an else, or a return, or something.
except ad doesn't show and the program continues to its force close.
Your dialog will not appear until the main application thread gets control again to process your request -- show() is asynchronous. You are crashing before then, most likely.
In short, your strategy for dealing with your parsing problem is fundamentally flawed.
The Commonsware response s correct. Let me try and say the same thing in different words.
An alert dialog does NOT interrupt the flow of control. It is just "left showing" when the program is waiting for input.
thus the sequence
showAlert("this is a message);
showGallery();
return;
this shows only momentarily.
A way out of this is to put the showGallery() function call inside the Positive response from the AlertDialog.
So to put it another way. If you want to interrupt the flow of your app with an AlertDialog (which is wisely pointed out is the wrong thing to want) then put the code you want executed after the dialog into the onClick callback of the AlertDialog.
OK, I had a similar situation. I was expecting a dialog to pop-up but it didn't. Instead, an exception occurred. The place where the exception occurred was positioned a couple of rows behind the place where I was expecting the dialog. I fixed this exception and then my dialog appeared.
It looks strange, and I think the dialog needs time to appear while the program just continues to run and then the program encounter the exception, chronological (but not programatically) before the dialog.
That's why I got dialog after I fixed the exception place.

Android: When to use Dialog vs. Activity

When is it preferable to use a Dialog box as opposed to an Activity in Android? From my understanding, anything you can do with a Dialog box you can also accomplish with an Activity. Are there any tasks that can only be accomplished by an Activity or a Dialog?
Is what you're doing worth a new Activity? Do you need to be able to start it through an intent? Do you really need to create a new Java class for it?
If it's a straightforward dialog that displays a text and has simple hooks for positive/negative/dismissal functions, definitely use a dialog.
If you have something complex, you may want to go for a full-blown activity.
Well why exactly would you want to start a new activity just to ask the user "Are you sure? Y/N"? Dialogs generally run on top of the activity, and are usually smaller activities or notifications for the user. They also usually have something to do with the process of the app running. It helps make things simpler to open a dialog to prompt the user on top of your activity, than to start a new activity atop your current activity.
I went for Activities when I needed an user interaction that needs backstack, navigation, lifecycle and callable features.. else with dialogs. Being from the WebApp world I ask whether I would have needed a new server page or a pop window for an interaction and the decision in Andoird world becomes easier!
If newServer page then mostly Activity
elseIf popUpWindow then dialog
I created my android application in one fragment with nested alert dialog, so far my application still running well in handle those nested dialog, and I think dialog is less consuming memory than an activity

nested AlertDialogs in android

I'm trying to display an AlertDialog inside of another AlertDialog. When the user clicks on the any item within the initial AlertDialog another AlertDialog is created and shown.
I'm following the correct pattern for creating and displaying AlertDialogs, the problem is as soon as the code reaches the point where the innerDialog.show() method is encountered the application fails. The logcat prints an uncaught runtime exception:
android.view.WindowManager$BadTokenException : Unable to add window -- token null is not for an applicaion
I'm wondering if i'm allowed to call the show() method on the innerAlertDialog manually.
The outer AlertDialog is working because i'm using the callback onCreateDialog() method.
In previous versions there was a bug where getApplicationContext() returned null.
I still dont quite if it has been fixed however with dialogs, its always better to send this.
And for the main question, its working as designed to avoid locking the UI thread.
I have seen people recommending creating a new layout with the theme of the dialog and start the activity on the first dialog, however I havent try this yet.

Categories

Resources