0

我有一个异步任务,我想让它在一段时间后取消,例如 60 秒。我想我必须在一段时间内声明它,但我不知道如何计算时间。

4

3 回答 3

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

    }

}
于 2013-09-02T19:47:01.673 回答
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
        }
    }
}
于 2013-09-02T19:35:51.103 回答
0

启动AsyncTask后,保留对它的引用并在 60 秒后调用 cancel,可能在 UI Thread 上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
        ...
    }
于 2013-09-02T19:47:50.590 回答