1

在我的代码中,我有一个线程。你可以看到线程的代码,

public class MainAsyncHome extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {

            return null;
        }

        @Override
        protected void onPostExecute(String xml) {


        }

        @Override
        protected void onPreExecute() {


        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }


    }

我按以下方式在我的主要活动 onCreate 方法中运行此线程

new MainAsyncHome().execute(null);

但我想给这个线程时间。这意味着当主要活动运行时我想晚点运行这个线程。我知道它可以使用睡眠方法。但是我怎么能迟到以这种方式运行这个线程。我被这个问题困住了。请给我答案。谢谢

4

3 回答 3

4

使用Handler 类,并定义 Runnable handleMyAsyncTask ,它将包含在 3000 毫秒延迟后执行的代码:

mHandler.postDelayed(MainAsyncHome, 1000*3); //Delay of three seconds

答案取自这里

把它放在代码中:

private final static int INTERVAL = 1000 * 3; //3 seconds
Handler m_handler;

Runnable MainAsyncHome = new Runnable()
{
     @Override 
     public void run() {
          doSomething();
          m_handler.postDelayed(MainAsyncHome, INTERVAL);
     }
}

void startRepeatingTask()
{
    MainAsyncHome.run(); 
}

void stopRepeatingTask()
{
    mHandler.removeCallback(MainAsyncHome);
}

希望它有效。

于 2013-07-04T12:37:18.360 回答
0

我通常使用CountDownTimer,假设延迟 3 秒:

CountDownTimer timer = new CountDownTimer(3000, 1000) {

     public void onTick(long millisUntilFinished) {

     }

     public void onFinish() {
         //do things, start your Task
         //remember we are still in the main thread!
     }
  }.start();

获取更多信息:http: //developer.android.com/reference/android/os/CountDownTimer.html

于 2013-07-04T12:53:03.150 回答
0

使用CountDownTimer这样的。

在onCreate中启动你的计时器。

CountDownTimer timer=new CountDownTimer(Delay,TimeIntervalToCallOnTick) {

            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onFinish() {
                // TODO Auto-generated method stub
                //start your asynctask
            }
        };
于 2013-07-04T12:55:02.533 回答