在新线程中注册来自服务的广播接收器

时间:2012-05-21 09:01:26

标签: android multithreading broadcastreceiver scheduler

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

我已经查看了这篇文章Are Android's BroadcastReceivers started in a new thread?,但我需要一个更具体的例子来说明使用Context.registerReceiver(BroadcastReceiver接收器,IntentFilter过滤器,String broadcastPermission,Handler调度程序)

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

非常感谢你。 RA

1 个答案:

答案 0 :(得分:12)

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