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

前端 未结 4 1850
一生所求
一生所求 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 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.

提交回复
热议问题