Should I manually close HandlerThreads created by my application when destroying the activity?

后端 未结 5 1934
独厮守ぢ
独厮守ぢ 2021-02-20 02:49

My app is composed of a single Activity. In this activity, I\'m creating multiple HandlerThreads which run in a loop to do socket blocking operations.<

5条回答
  •  孤独总比滥情好
    2021-02-20 03:13

        /**
     * Ask the currently running looper to quit.  If the thread has not
     * been started or has finished (that is if {@link #getLooper} returns
     * null), then false is returned.  Otherwise the looper is asked to
     * quit and true is returned.
     */
    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }
    

    Above is the 'quit' method of the source code of HandlerThread.java, just invoke it directly.

    Why should called quit? Below is 'run' method of the source code of HandlerThread.java.

        public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();//always loop except for a Message with null target
    
        mTid = -1;
    }
    

    The answer is 'loop is a 'while(true)' method,It will return until receive a Message with null target.

提交回复
热议问题