所以我的应用程序有一个计时器,它在倒计时时显示在主要活动中。我希望在计时器完成时播放警报,因此我安排了一个使用 AlarmManager 和一个扩展 BroadcastReceiver 的类来发出警报的意图。
一切正常,直到闹钟响起。我将崩溃追溯到我在 AlertDialog 上调用 show() 的那一行。我觉得它与应用程序上下文和代码不在 MainActivity 或其他东西有关,但我似乎找不到任何具有类似配置和相同崩溃源的东西。
这是警报对话框代码
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
以下是使用 MainActivity.java 中的 AlarmManager 进行调度的代码:
//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);
另外,顺便说一句,将 MainActivity.this 更改为 getApplicationContext() 以获取挂起的 Intent 并不能修复崩溃。看到很多人建议使用其中一种,但无论我使用哪一种,我的崩溃仍然存在。