用线程服务。延迟后如何重启一些线程?

时间:2013-03-07 13:22:18

标签: java android multithreading handler

我正在尝试使用Handler,但我的处理程序想要是静态的,所以我不能使用startThread方法。

这是Handler

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);

我不需要任何泄漏,所以我正在寻找正确的方法来完成这项任务。

1 个答案:

答案 0 :(得分:1)

我编写了一些示例代码,您在其中使用AsyncTask,并让它的回调确定您是否应该创建一个新的AsyncTask。请告诉我它是否错误。

TestFragment:

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();
        }
    }
}