How to stop a timer after certain number of times

后端 未结 3 833
醉话见心
醉话见心 2021-01-12 04:06

Trying to use a Timer to do run this 4 times with intervals of 10 seconds each.

I have tried stopping it with a loop, but it keeps crashing. Have tried

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-12 04:29

    Why not use an AsyncTask and just have it Thread.sleep(10000) and the publishProgress in a while loop? Here is what it would look like:

    new AsyncTask() {
    
            @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();
    

    Also as a side note, for longer term repetitive tasks, consider using AlarmManager...

提交回复
热议问题