android - android中的广播接收器和结果接收器

标签 android

BroadcastReceiverResultReceiver在android中有什么区别?

最佳答案

结果接收者:

Generic interface for receiving a callback result from someone.

广播接收器:

Base class for code that will receive intents sent by sendBroadcast().

编辑:

背景:所有网络操作/长时间运行的操作都应远离主线程。两种方法:

  1. 异步任务 - 对于简单的网络,比如说检索图像/做数据库 处理
  2. 服务 - 用于复杂的长时间运行的后台进程

如果您需要在主线程之外执行工作,但仅在用户与您的应用程序交互时执行,那么您可能应该创建一个新线程而不是服务。例如,如果您想播放一些音乐,但仅在您的 Activity 正在运行时,您可能会创建一个异步线程。但是,如果您希望即使在用户退出应用程序(例如下载)后仍继续该过程,那么请使用服务

假设你选择了 2。现在

  1. 您的 Activity 向您的服务发送网络请求

  2. 您的服务使用 DefaultHttpClient 执行该操作

  3. 它将数据发送回您的 Activity 。

    这里第三步接收数据可以通过两种方式完成

1.) Broadcast receiver: Multiple receivers can receive your data. Used if you want to send data/notifications across applications(say you are also interacting with fb and twitter, multiple receivers for your web broadcast), whenever you send broadcast its sent system wide.

2.) Result receiver: Your application is the only receiver of the data. It is an Interface you implement and pass it to the intentService through putExtra. IntentService will then fetch this object and call its receiver.send function to send anything (in bundle) to calling activity. Result receiver has preference over broadcast receivers if your all communication is internal to your application

编辑:我也应该提一下这个警告

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

关于android - android中的广播接收器和结果接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13178075/

相关文章:

android - 使用已完成的 Activity 和低 kb 图像获取 OutofMemoryError/InvocationTargetException?

android - 防止周末重复报警

android - 无法解析符号 v7 : import android. support.v7.widget.RecyclerView

Android listview多选

android - 将当前日期保存到数据库中

java - 检查android应用程序中的空字段

java - Eclipse 样式值错误

java - 如何判断 ListView 中选定的索引是文件还是目录?

java - 如何使用Android的加速度计

java - 如何在一个项目中同时使用Androidx库和支持库?