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

前端 未结 4 1842
一生所求
一生所求 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();   
    }
    
    0 讨论(0)
  • 2020-12-17 04:55

    I perform this way. In your activity

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

    in your Thread

    @Override
    public void run() {
        // stop your thread
        if (interrupted()) {
            return;
        }
        // do your work
    }
    
    0 讨论(0)
  • 2020-12-17 05:05

    Adding finish(); should end the Activity when onDestroy() or anything else (eg. a button is pressed) is called. When you use onDestroy(), make sure super.onDestroy(); is put after everything else is called.

    0 讨论(0)
  • 2020-12-17 05:12

    trying to stop the thread from outside is not reliable.

    I suggest to use global param using SharePreferences or Application Context, ( e.g. IS_APP_ACTIVE ) across your app
    and let thread kill itself.

    let me try to explain a bit...

    in your Activity

    protected void onResume() {
            super.onResume();
    
    // isAppActive
            CommonUtils.setAppActive(mContext, true);
    }
    
    protected void onPause() {
            super.onPause();
    
    // isAppActive
            CommonUtils.setAppActive(mContext, true);
    }
    

    in your thread

    if ( !CommonUtils.isAppActive(mContext) )
    

    just get out of the thread loop.

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