通过 UI 或非 UI 线程发送广播?
sendBroadcast thru UI or non-UI thread?
在单独的线程中发送广播(在我的例子中是 ACTION_APPWIDGET_UPDATE)是否比 UI 线程(可运行)更好(为了性能)?或者在 UI 线程上这样做是否可以接受?
发送广播不是一个耗时(长运行)的过程。所以你也可以从主线程(UI线程)发送广播。
如您所知,BroadcastReceiver.onReceive 总是在 UI 线程中 运行。您动态注册接收器,您可以指定另一个线程处理 onReceive()。这是通过 registerReceiver() 的 Handler 参数完成的。
所以,如果你最好使用 through UI。
您可以阅读 sendBroadcast 的文档:
This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.
所以在UI线程
上调用它是绝对安全的
广播总是异步发送的,你不需要运行它在一个单独的线程中以避免阻塞UI线程。 sendBroadcast() 已经是非阻塞的。来自 sendBroadcast's documentation:
public abstract void sendBroadcast (Intent intent)
Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required
permission to be enforced. This call is asynchronous; it returns immediately, and you
will continue executing while the receivers are run ...
在我的一些应用程序的开发者控制台中,当多次调用 "sendBroadcast" 时,我检查了一些设备中的 ANR(UI 线程阻塞)(小于 0.5%)。为了解决我在后台线程中调用 sendBroadcast。
这么看来就算是异步调用多次也能阻塞
在单独的线程中发送广播(在我的例子中是 ACTION_APPWIDGET_UPDATE)是否比 UI 线程(可运行)更好(为了性能)?或者在 UI 线程上这样做是否可以接受?
发送广播不是一个耗时(长运行)的过程。所以你也可以从主线程(UI线程)发送广播。
如您所知,BroadcastReceiver.onReceive 总是在 UI 线程中 运行。您动态注册接收器,您可以指定另一个线程处理 onReceive()。这是通过 registerReceiver() 的 Handler 参数完成的。
所以,如果你最好使用 through UI。
您可以阅读 sendBroadcast 的文档:
This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.
所以在UI线程
上调用它是绝对安全的广播总是异步发送的,你不需要运行它在一个单独的线程中以避免阻塞UI线程。 sendBroadcast() 已经是非阻塞的。来自 sendBroadcast's documentation:
public abstract void sendBroadcast (Intent intent)
Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run ...
在我的一些应用程序的开发者控制台中,当多次调用 "sendBroadcast" 时,我检查了一些设备中的 ANR(UI 线程阻塞)(小于 0.5%)。为了解决我在后台线程中调用 sendBroadcast。
这么看来就算是异步调用多次也能阻塞