我正在创建一个警报应用程序,在指定的时间,AlarmBroadcast
启动。
我想在指定时间添加Alert Dialog
。
这就是我所做的。
public class AlarmBrodcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final AlertDialog alertDialog = new AlertDialog.Builder(context.getApplicationContext()).create();
alertDialog.setTitle("Delete Remainder");
alertDialog.setMessage("Are you sure you want to Delete this Remainder");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
这给了我以下错误消息。
java.lang.RuntimeException:无法实例化接收器 com.example.taha.alarmproject.AlarmBrodcast: java.lang.ClassCastException: com.example.taha.alarmproject.AlarmBrodcast无法强制转换为 android.content.BroadcastReceiver
修改 的 MainActivity
Intent intent = new Intent(this, AlarmBrodcast.class);
intent.putExtra("message", "Alarm Message 00001");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
/* alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);*/
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show();
我还尝试从Activity
启动BrodcastReceiver
,但也无法启动它。
答案 0 :(得分:1)
一个简单的解决方案是使用create
。这就是你在我的项目中使用的一个漂亮的小库的方法:
Event
将该单行添加到compile 'org.greenrobot:eventbus:3.0.0'
(模块级)文件中。
这里的想法是让build.gradle
在调用AlarmBroadcast
时通知某个Activity
课程。
创建一个onReceive
课程来代表您的活动!
Plain Old Java Object (POJO)
现在,public class BroadCastEvent{
private boolean isCompleted;
BroadCastEvent(boolean completed){
this.isCompleted = completed;
}
//getter
public boolean isCompleted(){
return this.isCompleted;
}
}
类的onReceive
方法内部:
AlarmBroadcast
接下来,在您的活动中,注册以收听此事件:
EventBus.getDefault().post(new BroadCastEvent(true));
然后覆盖此方法:
EventBus.getDefault().register(this);
接下来,在onDestroy方法中取消注册eventbus:
public void onEvent(BroadCastEvent event){
if(event.isCompleted()){
//show your dialog here or start next activity
}
}
这会解耦您的代码,并允许您将AlarmBroadcast类设为@Override
public void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
,将您的活动设为Publisher
!
我希望这会有所帮助,请让我知道它是怎么回事!