在 Android 开发中,通常情况下我们会使用 AsyncTask 或 HandlerThread 等方式来创建一个后台线程(Background Thread)。但是,这些方法内部都会创建一个 Looper 对象,用于将消息队列与该线程关联起来,以便处理异步消息等操作。
但是,有时候我们也可能需要创建一个没有 Looper 对象的后台线程,例如在 IntentService 中执行耗时任务时,由于 IntentService 内部已经有了自己的 Looper,不需要再创建一个新的 Looper 对象。此时,我们就需要在创建后台线程时避免创建 Looper 对象。
以下是一个简单的示例代码,可以创建一个没有 Looper 对象的后台线程:
public class BackgroundThreadWithoutLooper extends Thread {
private Handler mHandler;
public BackgroundThreadWithoutLooper(Handler handler) {
mHandler = handler;
}
@Override
public void run() {
Looper.prepare(); // 临时创建一个 Looper,用于在后台线程中使用 Handler
mHandler = new Handler(Looper.myLooper()); // 将 Handler 与该 Looper 绑定
Looper.loop(); // 启动消息循环,处理异步消息等操作
}
// 使用该 Handler 对象向后台线程发送消息
public Handler getHandler() {
return mHandler;
}
}
在使用该类创建后台线程时,可以按照以下步骤进行操作:
// 在主线程中创建一个 Handler 对象
Handler handler = new Handler();
// 在后台线程中创建一个没有 Looper 对象的 Handler 对象
BackgroundThreadWithoutLooper thread = new BackgroundThreadWithoutLooper(handler);
thread.start(); // 启动后台线程
// 在主线程中使用上述创建的 Handler 对象向后台线程发送消息
Message msg = thread.getHandler().obtainMessage();
msg.what = MSG_WHAT;
thread.getHandler().sendMessage(msg);
通过上述代码示例,我们可以实