我正在尝试使用Handler来执行此操作,但是我的Handler希望是静态的,因此无法使用startThread
方法。
这是处理程序
private class ServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Integer tmp = msg.what;
Log.d(Tag, tmp.toString());
switch (msg.what) {
case THREAD_SYNC_START:
startSyncThread();
break;
case THREAD_SYNC_STOP:
mSyncThread.interrupt();
break;
default:
break;
}
}
}
这是我服务启动线程的方法
private void startSyncThread() {
if (mSyncThread != null) mSyncThread.interrupt();
mSyncThread = new SyncThread();
mSyncThread.start();
}
线程向处理程序发送消息
mServiceHandler.sendEmptyMessageDelayed(THREAD_SYNC_START, 2000);
我不需要任何泄漏,因此我正在寻找执行此任务的正确方法。
最佳答案
我编写了一些示例代码,在其中使用AsyncTask代替,然后让其回调以确定是否应该创建新的AsyncTask。请告诉我是否有错。
测试片段:
public class TestFragment extends Fragment {
private Handler mHandler;
/*
* Skipping most code and I will only show you the most essential.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
startAsyncTask(0);
}
private void startAsyncTask(long milisecondsToDelay) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
TestAsyncTask testAsyncTask = new TestAsyncTask(new FragmentCallback() {
@Override
public void onTaskDone() {
startAsyncTask(1000);
}
});
testAsyncTask.execute();
}
}, milisecondsToDelay);
}
public interface FragmentCallback {
public void onTaskDone();
}
}
TestAsyncTask:
public class TestAsyncTask extends AsyncTask<Void, Void, Void> {
private boolean mShouldCreateNewAsyncTask;
private FragmentCallback mFragmentCallback;
public TestAsyncTask(FragmentCallback fragmentCallback) {
mFragmentCallback = fragmentCallback;
}
@Override
protected Void doInBackground(Void... params) {
/*
* Do your loop or whatever and when you need to restart it set
* mShouldCreateNewAsyncTask = true and return null.
*/
mShouldCreateNewAsyncTask = true;
return null;
}
@Override
protected void onPostExecute(Void result) {
if (mShouldCreateNewAsyncTask) {
mFragmentCallback.onTaskDone();
}
}
}