从注册的服务的广播接收器在一个新的线程(Register a broadcast receiver

2019-07-29 11:25发布

我有开始长操作(上传过程)一broadcastreciever。 在服务的代码从活动开始类,我需要在一个新的线程来注册这个接收器。

我已经检查这个帖子是Android的BroadcastReceivers在一个新的线程开始了吗? 但我需要有关使用Context.registerReceiver一个更具体的例子(广播接收器接收器,过滤器的IntentFilter,字符串broadcastPermission,处理程序调度器)

其实我需要知道如何从服务中创建一个新的线程和注册接收器并连接到这个线程。

非常感谢你。 RA

Answer 1:

在您的服务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);


文章来源: Register a broadcast receiver from a service in a new thread