8

尝试使用 aTimer运行 4 次,每次间隔 10 秒。

我试过用循环停止它,但它一直在崩溃。尝试过使用schedule()三个参数,但我不知道在哪里实现一个计数器变量。有任何想法吗?

final Handler handler = new Handler(); 
Timer timer2 = new Timer(); 

TimerTask testing = new TimerTask() {
    public void run() { 
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "test",
                    Toast.LENGTH_SHORT).show();

            }
        });
    }
}; 

int DELAY = 10000;
for (int i = 0; i != 2 ;i++) {
    timer2.schedule(testing, DELAY);
    timer2.cancel();
    timer2.purge();
}
4

3 回答 3

13
private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
    private int counter = 0;
    public void run() {
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
            }
        });
        if(++counter == 4) {
            timer.cancel();
        }
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timer.schedule(task, DELAY, DELAY);
}
于 2012-07-15T07:04:08.537 回答
2

为什么不使用一个AsyncTask并且只使用它 Thread.sleep(10000) 和publishProgressin a while 循环?这是它的样子:

new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {

            int i = 0;
            while(i < 4) {
                Thread.sleep(10000);
                //Publish because onProgressUpdate runs on the UIThread
                publishProgress();
                i++;
            }

            // TODO Auto-generated method stub
            return null;
        }
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            //This is run on the UIThread and will actually Toast... Or update a View if you need it to!
            Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
        }

    }.execute();

另外作为旁注,对于长期重复性任务,请考虑使用AlarmManager...

于 2012-07-15T06:50:27.003 回答
1
for(int i = 0 ;i<4 ; i++){
    Runnable  runnableforadd ;
    Handler handlerforadd ;
    handlerforadd = new Handler();
    runnableforadd  = new Runnable() {
        @Override
        public void run() {
          //Your Code Here
            handlerforadd.postDelayed(runnableforadd, 10000);                         } 
    };
    handlerforadd.postDelayed(runnableforadd, i);

}
于 2012-07-15T06:59:34.917 回答