简体   繁体   English

Android将数据从IntentService发送到绑定的Activity

[英]Android Send data from IntentService to a bound Activity

I created an android app with an intent service bound to an activity. 我创建了一个将意图服务绑定到活动的android应用。 I followed this excellent article . 我关注了这篇出色的文章

But now I would like to send data from my IntentService to update my view (I mean, my activity). 但是现在我想从我的IntentService发送数据以更新我的视图(我的意思是我的活动)。

The context: I want to create a simple countdown. 上下文:我想创建一个简单的倒计时。 The service send the "time" to the activity every minute or second for example. 该服务例如每分钟或每秒将“时间”发送给活动。

How can I send data from my IntentService to my Activity ? 如何将数据从IntentService发送到Activity?

In kotlin please... Thank you! 请在科特林...谢谢!

In Android there are many APIs which allow us to send messages from a service to an activity. 在Android中,有许多API允许我们将消息从服​​务发送到活动。 Which API we should use that depends on whether the service and the activity are running in the same process or not. 我们应该使用哪个API取决于服务和活动是否在同一进程中运行。

If they are running in the same process, then you have 2 options 如果它们在同一进程中运行,那么您有2个选择

  • Using local broadcasts with LocalBroadcastManager . 通过LocalBroadcastManager使用本地广播。 It allows only components in an app communicate with other. 它仅允许应用程序中的组件与其他组件通信。 It is more secure and efficient than sending a global broadcast through the system. 它比通过系统发送全局广播更加安全和高效。
  • Using EventBus library if you don't want to implement broadcast receiver. 如果您不想实现广播接收器,请使用EventBus库。

If they are running in different processes, then you have 3 options 如果它们在不同的进程中运行,那么您有3个选择

  • Using Messenger (is coupled with a Handler ), messages will be processed on a single thread by the Handler sequentially. 使用Messenger (与Handler结合使用), Handler将在单个线程上顺序Handler
  • Using AIDL interface, the difference between Messenger and AIDL is AIDL can execute tasks on binder threads concurrently. 使用AIDL接口, MessengerAIDL之间的区别在于AIDL可以在活页夹线程上同时执行任务。
  • Using global broadcasts with BroadcastReceiver . BroadcastReceiver中使用全局广播

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM