gpt4 book ai didi

android - 在新线程中从服务注册广播接收器

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:41 25 4
gpt4 key购买 nike

我有一个开始长时间操作(上传过程)的广播接收器。在从 Activity 类启动的服务代码中,我需要在新线程中注册此接收器。

我已经查看了这篇文章Are Android's BroadcastReceivers started in a new thread?但是我需要一个关于使用 Context.registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) 的更具体的例子

实际上我需要知道如何从服务创建新线程并注册接收器并附加到该线程。

非常感谢。RA

最佳答案

在您服务的 onCreate() 中:

private Handler handler; // Handler for the separate Thread

HandlerThread handlerThread = new HandlerThread("MyNewThread");
handlerThread.start();
// Now get the Looper from the HandlerThread so that we can create a Handler that is attached to
// the HandlerThread
// NOTE: This call will block until the HandlerThread gets control and initializes its Looper
Looper looper = handlerThread.getLooper();
// Create a handler for the service
handler = new Handler(looper);
// Register the broadcast receiver to run on the separate Thread
registerReceiver (myReceiver, intentFilter, broadcastPermission, handler);

关于android - 在新线程中从服务注册广播接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10682241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com