fatal exception in android Timer

前端 未结 4 1574
旧时难觅i
旧时难觅i 2021-01-28 06:27

in my android application i\'m using Timer schedule.but getting Timer-0 fatal exception as below.how can i remove it.i have also mentioned code below -

01-28 13:         


        
相关标签:
4条回答
  • 2021-01-28 06:56

    You can use a CountDownTimer instead of the Timer :

    Timer timer = new CountDownTimer(Long.MAX_VALUE, 1000) {
        public void onTick(long millisUntilFinished) {
            // the code in the method run
        }
    
        public void onFinish() {
    
        }
    };
    

    The methods onTick and onFinish will be called in the UI thread.

    To make the timer start performing its action, run: timer.start()

    0 讨论(0)
  • 2021-01-28 07:01

    It is very simple, you are scheduling the Timer but not cancelling it never. So Task scheduled will be in the queue and wait for its turn. By that time it should get executed your Activity might not be in the foreground and it is unable to find the views. So it is throwing the Fatal Exception. Inorder, to get rid of the above issue, you need to cancel the tasks whenever you are going from that particular activity by calling myTimer.cancel().

    Or else

    Use the Handler class.

    0 讨论(0)
  • 2021-01-28 07:05

    use runOnUiThread for updating UI element from Timertask run Method as :

     myTimer.schedule(new TimerTask() {      
    
     @Override
     public void run() {
      Current_Activity.this.runOnUiThread(new Runnable() {
        public void run() {
            // update UI here
        }
     });
     }
    },0, 1000);
    
    0 讨论(0)
  • 2021-01-28 07:05
    runOnUiThread(new Runnable() {
         public void run() {
    
           //stuff that updates ui
    
        }
    });
    

    try this

    also look at

    Android "Only the original thread that created a view hierarchy can touch its views."

    CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch views

    Only the original thread that created a view hierarchy can touch its views

    0 讨论(0)
提交回复
热议问题