情况:活动在后台Thread中执行一些操作。当活动关闭时,android也会杀死线程。 我想把线程停止写入日志。有没有回调? (重写interrupt()和destroy()不起作用)或者我应该使用AsyncTask代替?
UPD: 线程代码
private class InternalReader extends Thread {
@Override
public void run() {
final int size = mReader.getDataSize();
final int blockSize = 10240;
int offset = 0;
TextFileCacher.DataBlock db = new TextFileCacher.DataBlock();
db.data = new char[blockSize];
int read = mReader.readString(offset, db.data, -1);
mListener.onRenderStarted();
mListener.onRenderReady();
while (read > 0){
db.size = read;
mCacher.processData(db);
offset+=read;
mListener.onProgress(offset/size);
read = mReader.readString(offset, db.data, -1);
}
mListener.onRenderReady();
}
}
AsyncTask代码
private class InternalReader extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
final int size = mReader.getDataSize();
final int blockSize = 10240;
int offset = 0;
TextFileCacher.DataBlock db = new TextFileCacher.DataBlock();
db.data = new char[blockSize];
int read = mReader.readString(offset, db.data, -1);
mListener.onRenderStarted();
mListener.onRenderReady();
while (read > 0){
db.size = read;
mCacher.processData(db);
offset+=read;
mListener.onProgress(offset/size);
read = mReader.readString(offset, db.data, -1);
}
mListener.onRenderReady();
return null;
}
}
初始化
(new InternalReader()).start();
和
(new InternalReader()).execute();