我试图在 Android 中实现可以在自己的线程中工作的对象(我不想公开处理程序,我想用自己的公共 api 包装 sendMessage 方法)。它具有将数据传递给对象的公共方法。该对象与活动生命周期(onResume、onPause)相关联。我想使用循环器和处理程序,而不仅仅是带有无限循环的纯 Java 线程。我想在恢复时启动工作线程并停止处理暂停回调。对象必须无限等待新消息。这是我下面的代码:
public class ThreadingObject {
private MyThread thread;
public ThreadingObject() {}
public void onResume() {
thread = new MyThread();
thread.startWorking();
}
public void onPause() {
thread.stopWorking();
}
public void setMessage(Object object) {
Message msg = new Message();
msg.obj = object;
thread.handler.sendMessage(msg);
}
protected void work(Object object) {
//Do something with object in own thread
}
private class MyThread extends Thread {
public Handler handler;
@Override
public void run() {
Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
ThreadingObject.this.work((String[]) msg.obj);
}
};
Looper.loop();
}
public void startWorking() {
start();
}
public void stopWorking() {
handler.getLooper().quit();
}
}
}
是正确的实现吗?我收到警告:“向死线程上的处理程序发送消息”。有什么我看不到的问题吗?