Reputation: 3921
So my app has a timer that displays in the main activity as it is counting down. I want an alarm to play when the timer is done, so I schedule an intent that sounds the alarm using AlarmManager and a class to extend BroadcastReceiver.
Everything works fine until the alarm goes off. I traced the crash to the line where I call show() on my AlertDialog. I feel like it has something to do with the application context and the code not being in MainActivity or something, but I can't seem to find anything with a similar configuration and the same crash source.
Here is the alert dialog code
public class SoundAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
...///Play sound code is here and works
final CharSequence [] options = {"OK"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setMessage("Beer is done!");
builder.setCancelable(false);
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(which == 0) {
mp.stop();
mp.release();
}
}
});
AlertDialog alert = builder.create();
alert.show();
... //other stuff
Here is the code that schedules with the AlarmManager which is found in MainActivity.java:
//Schedule the alarm
Intent alarmIntent = new Intent(MainActivity.this, SoundAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Calendar fireTime = Calendar.getInstance();
fireTime.setTimeInMillis(System.currentTimeMillis());
fireTime.add(Calendar.MILLISECOND, time);
alarmManager.set(AlarmManager.RTC_WAKEUP, fireTime.getTimeInMillis(), pendingIntent);
Also, as an aside, changing the MainActivity.this to getApplicationContext() for the pending intent does not fix the crash. Saw a lot of people suggesting using one or the other, but my crash persists no matter which one I use.
Upvotes: 0
Views: 1366
Reputation: 44571
I feel like it has something to do with the application context and the code not being in MainActivity or something,
Yes, you need an Activity
to show a Dialog
.
What you can do is build a separate Activity
with the layout
you want and start it from the Receiver
. You can add the following code to the <activity>
tag of your manifest.xml
to make it appear as a Dialog
.
android:theme="@android:style/Theme.Dialog"
Note: Activities provide a facility to manage the creation, saving and restoring of dialogs.
Upvotes: 1