如何从BroadcastReceiver类引发警报对话框?

时间:2011-08-29 12:15:49

标签: android broadcastreceiver

我在Activity课程中使用过计时器方法。在那个方法中,我有一个从Activity类到BroadcastReceiver类的意图。

BroadcastReceiver课程将使用AlarmManager在后​​台每15分钟拨打一次。

当我致电BroadcastReceiver课程时,我想提出AlertDialog

public void timerMethod(){
    Intent intent = new Intent(Activity.this,
      BroadcastReceiverClass.class
    );

    PendingIntent sender = PendingIntent.getBroadcast(
      QualityCallActivity.this,0, intent, 0
    );

    // We want the alarm to go off 30 seconds from now.
    long firstTime = SystemClock.elapsedRealtime();

    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    firstTime, 60*1000, sender);
}

BroadcastReceiverClass.java

public void onReceive(Context context, Intent intent)
{
    dialogMethod();
}

如何从后台流程中提取AlertDialogBroadcastReceiver

3 个答案:

答案 0 :(得分:7)

如果您的活动在BroadcastReceiver获取意图时正在运行,您应该能够使用runOnUiThread来运行创建AlertDialog的方法,例如:

public void onReceive(Context context, Intent intent)
{
    runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder d = new AlertDialog.Builder(MyActivity.this);
            b.setMessage("This is a dialog from within a BroadcastReceiver");
            b.create().show();
        }
    });

}

如果您将BroadcastReceiver设置为您的Activity的内部类,则此方法有效。

答案 1 :(得分:6)

简而言之:可能。

只有活动可以创建/显示对话框。事实上,这已被问过一次:

此外,这会给用户带来非常糟糕的体验:

  • 如果用户不在您的应用程序中(假设他正在播放 游戏)和你的Dialog每15分钟弹出一次,这将是非常的 为他烦恼。
  • 如果用户在您的应用程序中,还有其他几个(更好 适合的方式通知他已经执行了某些事情。

更适合的方式

事实上,您可以从BroadcastReceiver创建/显示Toast。当用户不在“您的应用程序中”时,也会显示此Toast

此外,您还可以从BroadcastReceiver发送通知(显示在屏幕顶部的通知栏中)。 tutorial on how to do this {与您在活动中的操作方式没有区别,只是您使用Context - 方法中传递的onReceive - 对象。

当用户不在“您的应用程序”中时,也会显示通知,并且IMO是此问题的最佳解决方案。

答案 2 :(得分:0)

1)在活动中:

public static Context ctx;

onCreate {
    ctx = this;
}

public void showAlertDialog(Context context, String title, String message) {

    final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting OK Button
    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Okay",
      new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) 
        {
            alertDialog.dismiss();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

2)在BroadcastReceiver.onReceive

YourActivity ac= new YourActivity ();
ac.showAlertDialog(YourActivity.ctx, "test", "test");
相关问题