[英]How to communicate between android and another process using broadcast receiver
我在我的活动和我的清单之间的另一个进程中定义的服务之间注册了一个broadcastReceiver
遇到问题。
我尝试了其他一些技巧,例如使用handlers
或ContentProvider
进行通信,但是它没有按我预期的那样工作,实际上,我想连续获取数据。
这是我在服务中的代码:
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 registered!
它在我的接收器中定义,但不起作用。
因此,在另一个process
定义的Activity和Service之间进行通信并连续获取数据的最佳方法是什么?
注意:我的服务从服务器获取数据,但服务器不是实时的,因此我通过使用handlers
定期向服务器请求来检查数据。
但这不起作用
那是因为您过度指定了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()
来限制向您自己的应用程序的交付。
在另一个流程中定义的Activity和Service之间进行通信并连续获取数据的最佳方法是什么?
如果我被迫进行此流程分离,那么我将考虑使用Messenger
。
我的服务从服务器获取数据,但服务器不是实时的,因此我通过使用处理程序定期向服务器请求来检查数据。
多年以来,这并不是推荐的模式。 请使用WorkManager
。 或者,使用JobScheduler
,如果你是不是在位置采用WorkManager
(因为它是AndroidX的一部分)。 无论采用哪种方法,您都可以摆脱第二个过程,从而大大简化了沟通。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.