是否可以从BrodcastReceiver启动警报对话框?

问题描述:

我正在创建一个闹钟应用程序,在指定的时间,AlarmBroadcast启动。 我想在指定的时间添加Alert Dialog是否可以从BrodcastReceiver启动警报对话框?

这就是我所做的。

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(); 

我也尝试从BrodcastReceiver启动Activity,但它也未能启动。

+1

您是否在清单中添加了'receiver'? –

+0

是的我添加了,我成功地能够打印吐司消息 – Kirmani88

+2

请发布代码,你实例化广播接收机 – Lino

一个简单的解决方案就是使用Event。这是你如何用一个漂亮的小库我在项目中使用做到这一点:

compile 'org.greenrobot:eventbus:3.0.0' 

是一行添加到您的build.gradle(模块级)文件。

这里的想法是在调用onReceive时,使AlarmBroadcast能够通知Activity类。

创建一个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); 

然后重写此方法:

public void onEvent(BroadCastEvent event){ 
    if(event.isCompleted()){ 
     //show your dialog here or start next activity 
    } 
} 

接下来,方法的onDestroy里面注销eventbus:

@Override 
public void onDestroy(){ 
    super.onDestroy(); 

    EventBus.getDefault().unregister(this); 
} 

这样可以使你的代码,并允许您,让您AlarmBroadcast类Publisher和活动为您提供Subscriber

我希望这可以帮助,请让我知道它是怎么回事!