show an alert dialog in broadcast receiver after a system reboot
The problem is you are trying to show an AlertDialog
from a BroadcastReceiver
, which isn't allowed. You can't show an AlertDialog
from a BroadcastReceiver
. Only activities can display dialogs.
You should do something else, have the BroadcastReceiver
start on boot as you do and start an activity to show the dialog.
Here is a blog post more on this.
EDIT:
Here is how I would recommend doing it. From your BroadcastReceiver
start an Activity
with an AlertDialog
as such..
public class NotifySMSReceived extends Activity
{
private static final String LOG_TAG = "SMSReceiver";
public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION);
this.registerReceiver(mReceivedSMSReceiver, filter);
}
private void displayAlert()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?").setCancelable(
false).setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION.equals(action))
{
//your SMS processing code
displayAlert();
}
}
}
}
As you see here I NEVER called setContentView()
. This is because the activity will have a transparent view and only the alert dialog will show.
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.
How do you use an alert dialog box in a broadcast receiver in android?
I'm not sure your title and your question match up, but if what you want is to open up a website in the browser just fire off an Intent from within your BroadcastReceiver.
If you want an explicit AlertDialog then see AlertDialog from within BroadcastReceiver?? Can it be done? for some detail: you will have to use an Intent and start an Activity with the new task flag set.
EDIT: you'd do something like this:
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, {CLASSNAME}.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
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 :)
Displaying a message from BroadcastReceiver
If you want to show a dialog from inside your onReceive of the BroadcastReceiver, you have to 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..
Your Broadcast Receiver onReceive
@Override
public void onReceive(Context context, Intent intent) {
Log.i("CallReceiverBroadcast", "onReceive() is called. ");
TelephonyManager teleMgr =(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener psl = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.i("CallReceiverBroadcast", "onCallStateChanged() is called. ");
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.i("CallReceiverBroadcast", "Incoming call caught. Caller's number is " +incomingNumber + ".");
//start activity which has dialog
Intent i=new Intent(context,DialogActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
};
teleMgr.listen(psl, PhoneStateListener.LISTEN_CALL_STATE);
teleMgr.listen(psl, PhoneStateListener.LISTEN_NONE);
}
And your DiaLogActivity
public class DialogActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//dont call setcontent view
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?").setCancelable(
false).setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
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.
How to add AlertDialog in broadcast receiver class in android?
Create a Activity
in your application and start Activity
from your BroadcastReceiver
and now launch AlertDialog
within onCreate
method of Activity
create style.xml
inside res/values
folder and put this inside it
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#000000</item>
<item name="android:windowNoTitle">true</item>
</style>
make Activty
Transparent by putting android:theme="@style/Theme.Transparent"
as a attribute of Activity
in your AndroidManifest.xml
file so only AlertDialog
will be shown.
Starting an activity with alertDialog from a broadcast receiver running a startup
This can't work for the reason that you already explained yourself:
If the activity is not yet running, you can't start it and immediately
send a broadcast Intent. At the moment you send the broadcast Intent,
your activity hasn't yet started so your listener isn't registered.
You should just add the message information directly to the Intent that you use to start your activity, like this:
//Show/start activity
Intent sec=new Intent(context, SecureMessagesActivity.class);
sec.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
sec.putExtra("some_msg", "I will be sent!");
context.startActivity(sec);
Log.v(TAG, "Sent Intent intentReceivedSuccessSms");
Then, in onCreate()
and in onNewIntent()
you can get the extra and use that to show your dialog. You don't need the BroadcastReceiver
in your activity.
Related Topics
Android Timer Updating a Textview (Ui)
Best Way to Implement View.Onclicklistener in Android
Playing Bg Music Across Activities in Android
What Is the Certificate Enrollment Process
Sort Data to Recyclerview Based on Latest Date from Firebase
Stream Live Android Audio to Server
Decompile an APK, Modify It and Then Recompile It
How to Draw a Filled Triangle in Android Canvas
How to Check Wifi or 3G Network Is Available on Android Device
Which Android Data Storage Technique to Use
How to Change Text of a Textview in Navigation Drawer Header
Ksoap2 Org.Xmlpull.V1.Xmlpullparserexception Expected Start_Tag Error
Encoding Url Query Parameters in Java
Source Code Does Not Match the Bytecode' When Debugging on a Device
Concise Way of Writing New Dialogpreference Classes