Reputation: 139
I am trying to call a method (postMessage) through a broadcastReceiver by Passing the context but is not working.
What is the mistake ? I tried many things but still not working.
public class AlarmReceiver extends BroadcastReceiver implements
OnActivityResultListener {
public void onReceive(Context context, Intent intent) {
try {
controler(context);
} catch (Exception e) {
Toast.makeText(
context,
"There was an error somewhere",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
public void controler(Context context) {
String radioButtonName = MAinActivity.actionAlarmName(radioButtonName);
if (radioButtonName.equals("1")) {
// TODO
} else if (radioButtonName.equals("2")) {
postMessage(context);
}
}
public void postMessage(Context context) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// Yes button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
Upvotes: 0
Views: 345
Reputation: 26
If you want to show a dialog in receiver without activity context, you can you this:
dialog.getWindow.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
Do not forgot add permission in AndroidManifest.xml.
Upvotes: 1
Reputation: 2823
As stated in the official documentation of Android You cannot show dialog in your on recieve method.
Even though you want to show a dialog then u can user an alternative approach of starting a activity with dialog style or you can start an transparent activity which will show the alert dialog in their on create method.
Hope this helps:
Upvotes: 1
Reputation: 2421
The Context
you receive in onReceive()
of a BroadcastReceiver
is not Activity Context, its application context. You can not display dialogs with application context. Dialog should always be associated with an Activity
.
Upvotes: 2
Reputation: 440
Add your receiver in AndroidManifest
<receiver android:name=".AlarmReceiver" android:process=":remote" />
Upvotes: 1