5

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

我已经检查了这篇文章Android 的广播接收器是在新线程中开始的吗?但我需要一个关于使用 Context.registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) 的更具体的例子

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

非常感谢你。类风湿关节炎

4

1 回答 1

17

在您的服务中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);
于 2012-05-21T09:28:56.563 回答