How to setup Alertbox from BroadcastReceiver
Although you can not show AlertDialog from Receivers because it needs ActivityContext.
You have an alternate solution to show an Activity like AlertDialog from Receiver. This is possible.
To start Activity as dialog you should set theme of activity in manifest as <activity android:theme="@android:style/Theme.Dialog" />
Style Any Activity as an Alert Dialog in Android
To start Activity from Receiver use code like
//Intent mIntent = new Intent();
//mIntent.setClassName("com.test", "com.test.YourActivity");
Intent mIntent = new Intent(context,YourActivity.class) //Same as above two lines
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
And one more reason behind not using AlertDialog from receiver (Even if you managed to show AlertDialog) is
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. More...
So the better way is 'show notification' and alternate way is 'to use Activity as an Alert..'
Happy coding :)
How to raise an alert dialog from BroadcastReceiver class?
In short: It is not possible.
Only Activity's can create/show dialogs. In fact, this has been asked more then once:
- AlertDialog in BroadcastReceiver
- How can I display a dialog from an Android broadcast receiver?
Also, this would give a very bad user-experience:
- If the user is not in your application (let's say he's playing a
Game) and your Dialog pops up every 15 minutes, this will be very
annoying for him. - If the user is in your application, there are several other (better
suited) ways to notify him that something has been executed.
Better suited ways
In fact, you can create/show a Toast
from an BroadcastReceiver
. This Toast
will also bee shown when the user is not "in your application".
Also, you can send a Notification (shown in the Notification-Bar at the top of your screen) from a BroadcastReceiver
. A tutorial on how to do this (it does not differ from how you do it in an Activity, except that you use the passed Context
-Object from the onReceive
-method).
The Notification will also be shown when the user is not "in your application" and is IMO the best solution to this problem.
Call an activity Alert Box from Broadcast Receiver android
To done that:
1- define two BroadcastReceivers
the 1st one in the manifest with low priority and the 2nd one in each activity in your app (run time) with a higher priority.
The 1st BroadcastReceivers
should show a notification
and the 2nd broadcast should abort()
the broadcast and display the dialog.
2- send an ordered broadcast.
PS: you can create a BaseActivtiy witch extends Activity, and define the 2nd broadcast on it (dont foget to register and unregister the broadcast in onStart()
and onStop()
),
then make all your Activity`s extends the BaseActivtiy
BroadcastReceiver onReceive open dialog
If you want to show a dialog from inside your onReceive
of the BroadcastReceiver, inside your broadcast receiver you may start a transparent activity with an alert dialog and NEVER called setContentView()
. The activity will have an transparent view and only the alert dialog will show.
Source: show an alert dialog in broadcast receiver after a system reboot
There are many similar posts which talk about this topic. See below questions for code samples and other reviews on the same:
AlertDialog from within BroadcastReceiver?? Can it be done?
How to raise an alert dialog from BroadcastReceiver class?
How can I display a dialog from an Android broadcast receiver?
How to setup Alertbox from BroadcastReceiver
Hope this will help.
Display Alertbox from service
A Service cannot show a Dialog
, only you can show short lived Toast
from there.
But If your Requirement is of showing dialog I will not disappoint you .You have got following options:
- If you have a
MainActivity
use aLocalBroadcastReceiver
to send a broadcast to your activity and let your MainActivity show a Dialog. (This will be possible only when your activity is visible) - The other option is Define a Dialog theme activity (take a look here) in your manifest and start that activity from service.
- Another option could be , Define a Activitiy in Manifest whose sole purpose would be display a Dialog and start that activity from service
Edit
I have a suggestion , If you wish to present information to your users , you should use Notification . The main reason that you cannot show a dialog from service is that Google wants information to be decently presented to its users , instead of surprising them when suppose they are in middle of a call , or typing message etc.
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.
Alternative Solution
However If you persist I have another solution if you like hacking, (but I don't like hacks in good application).
How do i setup BroadcastReceiver to only display sms received from specific numbers?
Just put one if there :)
public class IncomingSms extends BroadcastReceiver {
private static final String MY_PHONE_NUMBER = "your number here";
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
if(!MY_PHONE_NUMBER.equals(phoneNumber)) {
return;
}
...
Related Topics
How to Stack Firebase Cloud Messaging Notifications When the Application Is Not Running
Android Studio: Exclude Resource File Under Resources Sourcesets
How to Create Ripple Effect in Simple Layout
Android: HTML Anchor Link Works Only Once in Webview
Using Picasso Library with Listview
Eclipse Can't Find Android.Support.V4.Widget.Swiperefreshlayout
How to Add Padding Between Menu Items in Android
Android Attaching Multiple Adapters to One Adapter
Recyclerview with Multiple Countdown Timers Causes Flickering
Android: Starting an Activity for a Different Third Party App
Adding a Progress Dialog in a Webview
Stop All Toast Messages When Going to Another Screen in Android
How to Filter Listview Using Getfilter() in Baseadapter
Widget Not Updated on Launcher Restart
How to Install Android Studio on Ubuntu
Listview: Textview with Linkmovementmethod Makes List Item Unclickable