安卓新手,请教 BroadcastReceiver 怎么访问 local 变量?

2021-03-14 00:17:39 +08:00
 gamesover

我尝试用 react native 调用 android 代码,基本功能是发送短信,然后读取短信发送报告,成功或者失败

但我在看代码时,对一点非常困惑,安卓在广播context.registerReceiver(new BroadcastReceiver()时,会告知是那条短信发送成功吗?

假设我非常密集的发送了 10 条短信,sendEvent(mReactContext, "sms_onDelivery", "SMS delivered");能传递 sms 的 id 或者 phoneNumber 出来吗? 我尝试直接sendEvent(mReactContext, "sms_onDelivery", phoneNumber + "SMS delivered");说无法读取本地变量,必须全局变量才行

但是全局变量的话每次调用 autoSend,不是立即将 phoneNumber 改写为最新发送的 phoneNumber 吗?

代码源 https://github.com/briankabiro/react-native-get-sms-android/blob/f40a861ce85bb54ee0b4bd7241b302e4114a91b9/android/src/main/java/com/react/SmsModule.java#L232

@ReactMethod
    public void autoSend(String phoneNumber, String message, final Callback errorCallback,
                         final Callback successCallback) {

        cb_autoSend_succ = successCallback;
        cb_autoSend_err = errorCallback;

        try {
           // 无关代码,略过

            //---when the SMS has been delivered---
            context.registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode()) {
                        case Activity.RESULT_OK:
                            sendEvent(mReactContext, "sms_onDelivery", "SMS delivered"); // 这怎么知道发送成功的是哪个短信?能传递 phoneNumber 出来吗?
                            break;
                        case Activity.RESULT_CANCELED:
                            sendEvent(mReactContext, "sms_onDelivery", "SMS not delivered");
                            break;
                    }
                }
            }, new IntentFilter(DELIVERED));
4144 次点击
所在节点    Android
4 条回复
susunus
2021-03-14 02:19:20 +08:00
广播监听到短信变化后,contentprovider 读下?
MapHacker
2021-03-14 14:03:11 +08:00
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0);

这个 new Intent(SENT)可以调用 putExtra 方法存一些数据,可以试试呢
然后在 onReceive 通过 arg1.getExtra 取到对应的值,不知道是否可行
gamesover
2021-03-14 21:49:02 +08:00
@MapHacker 服!
https://stackoverflow.com/a/4640066/2251303 后面有人评论里提到和你一样的办法

还有一个就是 PendingIntent.getBroadcast(context, `0`, new Intent(SENT), 0),第二个参数可以改为任意数字,那么我直接 pass sms 的数据库 id 就可以了
gamesover
2021-03-14 22:18:37 +08:00
不好意思,继续更正一下,https://stackoverflow.com/a/36408330/2251303
requstcode 无法在接受广播时提取,但是不同的 requstcode 还是有意义的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/761413

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX