[JAVA] Programming from 51 years old memorandum android Timer

Easy timer. The timer is a worker thread. But TimerTask has some unreliable behavior, so it seems to be Handler recommended. Also consider handler.postDelayed (runnable, delayMillis)!

The file to use is ・ Maina c Chity ty. See you Create an instance of Timer Create an instance of MyTimer Create ScheduleAtFixedRate method for Timer

・ My Chime r. See you Inherit TimerTask Create handle.post method of Handle and Runnable

MainActivity.java


public class MainActivity extends AppCompatActivity{

       @Override 
       protected void  onCreate(Bundle savedInstanceState){
                 super.onCreate(savedInstanceState);
                 setContentView(R.layout.activity_main);
       
                 Timer   timer   = new Timer();
                 MyTimer myTimer = new MyTimer(this);
                 timer.scheduleAtFixedRate(myTimer,0,10000);
       }
}

Project-> app-> src-> main-> java->

file name MyTimer
superclass TimerTask

MyTimer.java


public class   MyTimer extends TimerTask{
       private Handler  handler;
       private Context context;
       private TIMER_STOP;

       public  MyTimer(Context context){
               handler       = new Handler();
               this.context  = context;
               TIMER_STOP    = false;
        }

       @Override 
       public void run(){
              handler.post(new Runnable(){
                   @Override 
                   public void run(){
                          Toast.makeText(context,"Toast",Toast.LENGTH_SHORT).show();
                   if(TIMER_STOP){
                      cancel();
                   }
                   }
              });
        }

        public void TimerStop(){
               TIMER_STOP = true;
        }
}

By calling myTimer.TimerStop () from MyActivity.class, cancel () </ font> </ strong> will be executed and the timer will stop. In the thread stop process, there is a process to stop the thread with @Override public void run () { while (KEY) {todo} </ font>}, but <font color = "#" When I did that in the execution part of f55 "> Timer, the while statement was executed indefinitely for each timer </ font>. So I used if () {cancel ()}!

cancel () will be processed the next time the timer runs. For example, timer.scheduleAtFixedRate (my) With a timer set of Timer, 0,1000 * 60 * 60), it feels like cancel () is activated when the next timer task is executed (1 hour after the worst: 1000 * 60 * 60).

You may want to stop processing immediately and destroy the thread. But this is dangerous. When Thread is running normally, protected objects may become unstable due to Thread discard, resulting in unexpected behavior. It is difficult to find or identify objects that have been released from Thread, so consider whether you can design a program with interrupt () without discarding Thread.

Recommended Posts