java - 如何使用广播接收器在android和另一个进程之间进行通信

标签 java android broadcastreceiver android-broadcast

我在 Activity 和 Service 之间注册 broadcastReceiver 时遇到问题,该 Service 在 list 中的另一个进程中定义。

我尝试了一些其他技巧,例如使用 handlersContentProvider 用于通信,但它没有按我的预期工作,事实上我想连续获取数据。

这是我的服务中的代码:

Intent locationIntent = new Intent("LocationIntent");
        locationIntent.setAction("updatedLocations");
        locationIntent.setClass(getApplicationContext(), MapBoxActivity.class);
        locationIntent.putExtra("list",updatedList);
        sendBroadcast(locationIntent);

我在 Activity 的 OnCreate 中注册它:

updatedLocationBroadcast = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Timber.tag("localB").d("registered!");
                if (intent != null && intent.getAction() != null && intent.getAction().equals("updatedLocations")) {
                    sawLocationsList = (HashMap<Integer, MarkerItem>)intent.getSerializableExtra("list");
                    Timber.tag("sawL").d("updated" + sawLocationsList.toString());
                }
            }
        };
registerReceiver(updatedLocationBroadcast , new IntentFilter("updatedLocations"));

正如我所料,我想查看我的 broadcastReceiver 寄存器和我的 Timber 日志 localB 已注册! 这是在我的接收器中定义的,但它不起作用。

那么,在另一个进程中定义的 Activity 和 Service 之间进行通信并持续获取数据的最佳方式是什么???

注意:我的服务从服务器获取数据,但服务器不是实时的,因此我通过使用处理程序定期向服务器请求来检查数据。

最佳答案

but it doesn't work

那是因为你过度指定了你的 Intent 。替换:

    Intent locationIntent = new Intent("LocationIntent");
    locationIntent.setAction("updatedLocations");
    locationIntent.setClass(getApplicationContext(), MapBoxActivity.class);
    locationIntent.putExtra("list",updatedList);
    sendBroadcast(locationIntent);

与:

    Intent locationIntent = new Intent("updatedLocations");
    locationIntent.putExtra("list",updatedList);
    sendBroadcast(locationIntent);

但请注意,任何应用程序都可以收听此广播。考虑在 Intent 上使用 setPackage() 来限制向您自己的应用程序的交付。

What's the best way to communicate between Activity and Service defined in another process and getting data continuously?

如果我被迫进行这种进程分离,我会考虑 Messenger

my service gets data from server but the server is not realTime so I check the data by requesting periodically to server using handlers.

多年来,这一直不是推荐的模式。请使用WorkManager。或者,如果您无法采用 WorkManager(因为它是 AndroidX 的一部分),请使用 JobScheduler。在这两种方法中,您都可以摆脱第二个流程并大大简化您的通信。

关于java - 如何使用广播接收器在android和另一个进程之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56153023/

相关文章:

java - Singleton Sqlite 基类的覆盖方法

java - 如何使用 Dagger-2 延迟注入(inject)接口(interface)?

java - 如何将数据存储到哈希表中 - java

Android:如何设置 ImageButton 的 src 图像的高度/宽度?

android - Firebase 使用 Hashmap 在同一个 child 上推送数据

android - 手机休眠时听信号强度

java - 当手机处于深度 sleep 时接收音量键按下事件

java - 将对象添加到 ArrayList 并在 Java 中给出 NullPointerException

android - 在 recyclerview 中滚动到顶部加载更多数据

android - 在 Broadcastreceiver 中访问 SQL