How to stop a running thread when Activity on destroy at Android?

前端 未结 4 1843
一生所求
一生所求 2020-12-17 04:15

I used some thread objects in my Android activity. But these threads do not stop itself when Activity on destroy. My code for thread-stopping as following:



        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 04:51

    try this way:

    volatile boolean stop = false;
    
    public void run() {
        while ( !stop ) {
         log.v("Thread", "Thread running..." );
          try {
          Thread.sleep( 1000 );
          } catch ( InterruptedException e ) {
          log.v("Thread","Thread interrupted..." );
          }
        }
    }
    
    @Override
    public void onDestroy() {
        stop = true;
        super.onDestroy();
    
    }
    

    and

    @Override
    public void onDestroy() {
        thread.interrupt();
        super.onDestroy();   
    }
    

提交回复
热议问题