【问题标题】:AlertDialog from within BroadcastReceiver?? Can it be done?BroadcastReceiver中的AlertDialog??可以做到吗?
【发布时间】:2011-06-18 03:49:26
【问题描述】:

BroadcastReceiver 中的AlertDialog?可以做到吗?我正在开发一个应用程序,如果我收到短信,它会弹出一个对话框。我正在尝试在 BroadcaseReceiver 中对此进行编码。但是我不能使用这行代码AlertDialog.Builder builder = new AlertDialog.Builder(this);。有人可以帮我一个提示吗!

public class SMSPopUpReceiver extends BroadcastReceiver {

    private static final String LOG_TAG = "SMSReceiver";
    public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
    static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    public void onReceive(Context context, Intent intent) {
        Log.i(LOG_TAG, "onReceive");

        if (intent.getAction().equals(SMSPopUpReceiver.ACTION)) {
            StringBuilder sb = new StringBuilder();
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");

            for (Object pdu : pdus){
                    SmsMessage messages =
            SmsMessage.createFromPdu((byte[]) pdu);

            sb.append("Received SMS\nFrom: ");
            sb.append(messages.getDisplayOriginatingAddress());
            sb.append("\n----Message----\n");
            sb.append( messages.getDisplayMessageBody());
            }
            }
            Log.i(SMSPopUpReceiver.LOG_TAG,
            "[SMSApp] onReceiveIntent: " + sb);
            Toast.makeText
            (context, sb.toString(), Toast.LENGTH_LONG).show();
            }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       dialog.cancel();
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
    }

}

【问题讨论】:

  • 为什么不能使用AlertDialog.Builder builder = new AlertDialog.Builder(this); 是不是对this 参考不满意?如果是这种情况,请尝试将其替换为对 getApplicationContext() 的调用。我不确定这是否是您遇到的问题。我觉得在这种情况下,对话框只会在 BroadcastReceiver 返回之前在屏幕上闪烁一秒钟。
  • 不能使用 getApplicationContext() !
  • 自发弹出一个对话框(从用户的角度来看)对我来说听起来像是糟糕的 UI 设计。为什么不使用通知?这就是他们的目的。
  • 这是完整的例子,通过链接stackoverflow.com/a/41137562/4344659

标签: java android broadcastreceiver android-alertdialog


【解决方案1】:

主要问题:尽量避免将耗时的功能放入 BroadcastReceiver。它应该只是在绑定的 Activity/Service 中接收并启动进一步的处理。

更新:

请查看以下可能有用的来源:

StackOverflow 上的类似问题:

How to send data from BroadcastReceiver to an Activity in android?

Android SMS receiver not working

Android SDK 演示示例:

android-sdk-windows\samples\android-8\ApiDemos\src\com\example\android\apis\os\SmsMessagingDemo.java

当然还有标准的 Android API 文档:http://developer.android.com/reference/android/content/BroadcastReceiver.html

更新2:

添加了应有的应用框架。请注意,没有定义任何内容视图。这是因为您的应用程序将具有透明屏幕。实现这一目标

@android:style/Theme.Translucent

在 AndroidManifest.xml 中的此活动的主题标记下输入。

public class NotifySMSReceived extends Activity 
{
    private static final String LOG_TAG = "SMSReceiver";
    public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
    static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IntentFilter filter = new IntentFilter(ACTION);
        this.registerReceiver(mReceivedSMSReceiver, filter);
    }

    private void displayAlert()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?").setCancelable(
                false).setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION.equals(action)) 
            {
                //your SMS processing code
                displayAlert();
            }
        }
    };    
}

【讨论】:

  • 我认为你是对的。你能帮我解决这个问题吗!
  • 我建议您创建具有透明背景的服务或活动并将广播接收器绑定到它。检查一些 Android SDK 示例。此外,我的个人资料下还有一些有用的问题/答案。
  • 你能告诉我去哪里看吗,我是新手。 googletalk我如果你想口吃约翰史密斯
  • 更新了我的答案以包含有用的知识来源。
  • zelimir 我正在查看代码,但我仍然不明白。可以离线帮忙吗
【解决方案2】:

我一直在研究它,the documentation of the BroadcastReceiver 实际上说:

公共抽象无效 onReceive (上下文上下文,意图意图)

自:API 级别 1 此方法是 当 BroadcastReceiver 被调用时 接收 Intent 广播。期间 这次你可以使用其他 BroadcastReceiver 上的方法 查看/修改当前结果值。 该函数通常在内部调用 它进程的主线程,所以你 永远不应该执行长时间运行 其中的操作(有一个超时 系统允许的 10 秒 在考虑接收器之前 被阻止并被杀死的候选人)。 您无法在 你对 onReceive() 的实现。

您无法在 你的 onReceive() 实现

看来是不可能的

【讨论】:

    【解决方案3】:

    这已经晚了,但这可能会对某人有所帮助。

    您不能在广播接收器中使用警报对话框,我们只能在活动或服务中使用它。像这样试试

    在你的广播接收器的 onReceive 方法中添加

    Intent i = new Intent(context, yourclass.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
    

    在你的类中设置你的对话信息,这样当你触发接收器事件时它就会出现。我试过这个,它对我有用。希望这可以帮助一些人:-)

    【讨论】:

      【解决方案4】:

      您可以创建一个新的透明活动,然后在该活动中创建警报对话框,每当要显示警报时,请从您的广播接收器调用该活动,这可以工作,未经测试

      【讨论】:

        【解决方案5】:

        将 AlertDilaog 中的单词“this”替换为“context”——onRecieve 方法的第一个参数。

         public void onReceive(Context context, Intent intent)
        

        【讨论】:

        • 我尝试使用上下文,但我从来没有看到 Dilaog
        • 它永远不会出现,因为你必须show()它。 AlertDialog alert = builder.create(); alert.show();
        • 我是如何得到这个错误的:01-30 16:03:21.748: WARN/WindowManager(34): Attempted to add window with non-application token WindowToken{43c345e8 token=null}.中止。
        • @Java 评论:您是否按照 Umesh 的建议将代码更改为 `AlertDialog.Builder builder = new AlertDialog.Builder(context);`?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多