如何让异步任务工作并在一段时间后解散?

时间:2013-09-02 19:29:41

标签: android android-asynctask while-loop

我有一个asynctask,我想让它在一段时间后取消,例如60秒。 我想我必须在一段时间内使用它,但我不知道如何计算时间。

3 个答案:

答案 0 :(得分:1)

这是我的想法:

public class ThreadWithAutoCancel extends AsyncTask<Void, Void, Void> {

    public ThreadWithAutoCancel(int timeOut) {
        WatchDog watchDog = new WatchDog(this);
        watchDog.execute(timeOut);
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Do the job
        return null;
    }

    class WatchDog extends AsyncTask<Integer,Void,Void>{

        private long startTime;
        private AsyncTask task;

        public WatchDog(AsyncTask taskToStop){
            task = taskToStop;
        }

        @Override
        protected void onPreExecute(){
            startTime = System.currentTimeMillis()/1000;
        }

        @Override
        protected Void doInBackground(Integer... params) {
            while(System.currentTimeMillis()/1000 < startTime+params[0]){

            }
            task.cancel(true);
            return null;
        }

    }

}

答案 1 :(得分:0)

您可以使用处理程序执行此操作。例如,在asynctask执行60秒后,此代码将在带有R.id.mytext的TextView上显示“已完成”:

final int FINISH = 1;
Thread waitingThread;
MyAsyncTask myAsyncTask;
Handler mHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        if (msg.what == FINISH)
        {
            myAsyncTask.cancel(true);
            ((TextView) findViewById(R.id.mytext)).setText("Completed");
        }
    };
};

// ...

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    waitingThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(60);

                mHandler.sendEmptyMessage(FINISH);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    myAsyncTask = new MyAsyncTask();
    myAsyncTask.execute();
    waitingThread.start();
}

private class MyAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        while (true) {
              // do something
        }
    }
}

答案 2 :(得分:0)

启动AsyncTask后,保留对它的引用并在60秒后调用取消,也许在UI线程Handler上。在doInBackground方法中,如果isCancelled返回true,则必须确保返回。我希望以下代码片段能够提供帮助:

public class MyActivity extends Activity {
    private Handler mHandler;
    private AsyncTask<?, ?, ?> mTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        mTask = new MyCustomTask();
        mTask.execute(1, 2, 3);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mTask.cancel();
            }, 60L);
    }
}

在您的自定义任务中:

public class MyCustomTask extends AsyncTask<Integer, Float, String> {
    @Override
    protected String doInBackground(Integer... params) {
        String output = "";
        for (Integer i : params) {
            // Check status for each param
            if (isCancelled()) {
                return output;
            }

            ...
         }
    }

    @Override
    protected void onCancelled(String result) {
        // This bit runs on the UI thread
        ...
    }