StateMachine.java revision ff4fcdb98c9575642c48f1daeafff4b257769e81
1/**
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.util;
18
19import android.os.Handler;
20import android.os.HandlerThread;
21import android.os.Looper;
22import android.os.Message;
23import android.text.TextUtils;
24import android.util.Log;
25
26import java.io.FileDescriptor;
27import java.io.PrintWriter;
28import java.util.ArrayList;
29import java.util.Calendar;
30import java.util.Collection;
31import java.util.HashMap;
32import java.util.Vector;
33
34/**
35 * {@hide}
36 *
37 * <p>The state machine defined here is a hierarchical state machine which processes messages
38 * and can have states arranged hierarchically.</p>
39 *
40 * <p>A state is a <code>State</code> object and must implement
41 * <code>processMessage</code> and optionally <code>enter/exit/getName</code>.
42 * The enter/exit methods are equivalent to the construction and destruction
43 * in Object Oriented programming and are used to perform initialization and
44 * cleanup of the state respectively. The <code>getName</code> method returns the
45 * name of the state the default implementation returns the class name it may be
46 * desirable to have this return the name of the state instance name instead.
47 * In particular if a particular state class has multiple instances.</p>
48 *
49 * <p>When a state machine is created <code>addState</code> is used to build the
50 * hierarchy and <code>setInitialState</code> is used to identify which of these
51 * is the initial state. After construction the programmer calls <code>start</code>
52 * which initializes and starts the state machine. The first action the StateMachine
53 * is to the invoke <code>enter</code> for all of the initial state's hierarchy,
54 * starting at its eldest parent. The calls to enter will be done in the context
55 * of the StateMachines Handler not in the context of the call to start and they
56 * will be invoked before any messages are processed. For example, given the simple
57 * state machine below mP1.enter will be invoked and then mS1.enter. Finally,
58 * messages sent to the state machine will be processed by the current state,
59 * in our simple state machine below that would initially be mS1.processMessage.</p>
60<code>
61        mP1
62       /   \
63      mS2   mS1 ----> initial state
64</code>
65 * <p>After the state machine is created and started, messages are sent to a state
66 * machine using <code>sendMessage</code> and the messages are created using
67 * <code>obtainMessage</code>. When the state machine receives a message the
68 * current state's <code>processMessage</code> is invoked. In the above example
69 * mS1.processMessage will be invoked first. The state may use <code>transitionTo</code>
70 * to change the current state to a new state</p>
71 *
72 * <p>Each state in the state machine may have a zero or one parent states and if
73 * a child state is unable to handle a message it may have the message processed
74 * by its parent by returning false or NOT_HANDLED. If a message is never processed
75 * <code>unhandledMessage</code> will be invoked to give one last chance for the state machine
76 * to process the message.</p>
77 *
78 * <p>When all processing is completed a state machine may choose to call
79 * <code>transitionToHaltingState</code>. When the current <code>processingMessage</code>
80 * returns the state machine will transfer to an internal <code>HaltingState</code>
81 * and invoke <code>halting</code>. Any message subsequently received by the state
82 * machine will cause <code>haltedProcessMessage</code> to be invoked.</p>
83 *
84 * <p>If it is desirable to completely stop the state machine call <code>quit</code> or
85 * <code>quitNow</code>. These will call <code>exit</code> of the current state and its parents,
86 * call <code>onQuiting</code> and then exit Thread/Loopers.</p>
87 *
88 * <p>In addition to <code>processMessage</code> each <code>State</code> has
89 * an <code>enter</code> method and <code>exit</exit> method which may be overridden.</p>
90 *
91 * <p>Since the states are arranged in a hierarchy transitioning to a new state
92 * causes current states to be exited and new states to be entered. To determine
93 * the list of states to be entered/exited the common parent closest to
94 * the current state is found. We then exit from the current state and its
95 * parent's up to but not including the common parent state and then enter all
96 * of the new states below the common parent down to the destination state.
97 * If there is no common parent all states are exited and then the new states
98 * are entered.</p>
99 *
100 * <p>Two other methods that states can use are <code>deferMessage</code> and
101 * <code>sendMessageAtFrontOfQueue</code>. The <code>sendMessageAtFrontOfQueue</code> sends
102 * a message but places it on the front of the queue rather than the back. The
103 * <code>deferMessage</code> causes the message to be saved on a list until a
104 * transition is made to a new state. At which time all of the deferred messages
105 * will be put on the front of the state machine queue with the oldest message
106 * at the front. These will then be processed by the new current state before
107 * any other messages that are on the queue or might be added later. Both of
108 * these are protected and may only be invoked from within a state machine.</p>
109 *
110 * <p>To illustrate some of these properties we'll use state machine with an 8
111 * state hierarchy:</p>
112<code>
113          mP0
114         /   \
115        mP1   mS0
116       /   \
117      mS2   mS1
118     /  \    \
119    mS3  mS4  mS5  ---> initial state
120</code>
121 * <p>After starting mS5 the list of active states is mP0, mP1, mS1 and mS5.
122 * So the order of calling processMessage when a message is received is mS5,
123 * mS1, mP1, mP0 assuming each processMessage indicates it can't handle this
124 * message by returning false or NOT_HANDLED.</p>
125 *
126 * <p>Now assume mS5.processMessage receives a message it can handle, and during
127 * the handling determines the machine should change states. It could call
128 * transitionTo(mS4) and return true or HANDLED. Immediately after returning from
129 * processMessage the state machine runtime will find the common parent,
130 * which is mP1. It will then call mS5.exit, mS1.exit, mS2.enter and then
131 * mS4.enter. The new list of active states is mP0, mP1, mS2 and mS4. So
132 * when the next message is received mS4.processMessage will be invoked.</p>
133 *
134 * <p>Now for some concrete examples, here is the canonical HelloWorld as a state machine.
135 * It responds with "Hello World" being printed to the log for every message.</p>
136<code>
137class HelloWorld extends StateMachine {
138    HelloWorld(String name) {
139        super(name);
140        addState(mState1);
141        setInitialState(mState1);
142    }
143
144    public static HelloWorld makeHelloWorld() {
145        HelloWorld hw = new HelloWorld("hw");
146        hw.start();
147        return hw;
148    }
149
150    class State1 extends State {
151        &#64;Override public boolean processMessage(Message message) {
152            log("Hello World");
153            return HANDLED;
154        }
155    }
156    State1 mState1 = new State1();
157}
158
159void testHelloWorld() {
160    HelloWorld hw = makeHelloWorld();
161    hw.sendMessage(hw.obtainMessage());
162}
163</code>
164 * <p>A more interesting state machine is one with four states
165 * with two independent parent states.</p>
166<code>
167        mP1      mP2
168       /   \
169      mS2   mS1
170</code>
171 * <p>Here is a description of this state machine using pseudo code.</p>
172 <code>
173state mP1 {
174     enter { log("mP1.enter"); }
175     exit { log("mP1.exit");  }
176     on msg {
177         CMD_2 {
178             send(CMD_3);
179             defer(msg);
180             transitonTo(mS2);
181             return HANDLED;
182         }
183         return NOT_HANDLED;
184     }
185}
186
187INITIAL
188state mS1 parent mP1 {
189     enter { log("mS1.enter"); }
190     exit  { log("mS1.exit");  }
191     on msg {
192         CMD_1 {
193             transitionTo(mS1);
194             return HANDLED;
195         }
196         return NOT_HANDLED;
197     }
198}
199
200state mS2 parent mP1 {
201     enter { log("mS2.enter"); }
202     exit  { log("mS2.exit");  }
203     on msg {
204         CMD_2 {
205             send(CMD_4);
206             return HANDLED;
207         }
208         CMD_3 {
209             defer(msg);
210             transitionTo(mP2);
211             return HANDLED;
212         }
213         return NOT_HANDLED;
214     }
215}
216
217state mP2 {
218     enter {
219         log("mP2.enter");
220         send(CMD_5);
221     }
222     exit { log("mP2.exit"); }
223     on msg {
224         CMD_3, CMD_4 { return HANDLED; }
225         CMD_5 {
226             transitionTo(HaltingState);
227             return HANDLED;
228         }
229         return NOT_HANDLED;
230     }
231}
232</code>
233 * <p>The implementation is below and also in StateMachineTest:</p>
234<code>
235class Hsm1 extends StateMachine {
236    public static final int CMD_1 = 1;
237    public static final int CMD_2 = 2;
238    public static final int CMD_3 = 3;
239    public static final int CMD_4 = 4;
240    public static final int CMD_5 = 5;
241
242    public static Hsm1 makeHsm1() {
243        log("makeHsm1 E");
244        Hsm1 sm = new Hsm1("hsm1");
245        sm.start();
246        log("makeHsm1 X");
247        return sm;
248    }
249
250    Hsm1(String name) {
251        super(name);
252        log("ctor E");
253
254        // Add states, use indentation to show hierarchy
255        addState(mP1);
256            addState(mS1, mP1);
257            addState(mS2, mP1);
258        addState(mP2);
259
260        // Set the initial state
261        setInitialState(mS1);
262        log("ctor X");
263    }
264
265    class P1 extends State {
266        &#64;Override public void enter() {
267            log("mP1.enter");
268        }
269        &#64;Override public boolean processMessage(Message message) {
270            boolean retVal;
271            log("mP1.processMessage what=" + message.what);
272            switch(message.what) {
273            case CMD_2:
274                // CMD_2 will arrive in mS2 before CMD_3
275                sendMessage(obtainMessage(CMD_3));
276                deferMessage(message);
277                transitionTo(mS2);
278                retVal = HANDLED;
279                break;
280            default:
281                // Any message we don't understand in this state invokes unhandledMessage
282                retVal = NOT_HANDLED;
283                break;
284            }
285            return retVal;
286        }
287        &#64;Override public void exit() {
288            log("mP1.exit");
289        }
290    }
291
292    class S1 extends State {
293        &#64;Override public void enter() {
294            log("mS1.enter");
295        }
296        &#64;Override public boolean processMessage(Message message) {
297            log("S1.processMessage what=" + message.what);
298            if (message.what == CMD_1) {
299                // Transition to ourself to show that enter/exit is called
300                transitionTo(mS1);
301                return HANDLED;
302            } else {
303                // Let parent process all other messages
304                return NOT_HANDLED;
305            }
306        }
307        &#64;Override public void exit() {
308            log("mS1.exit");
309        }
310    }
311
312    class S2 extends State {
313        &#64;Override public void enter() {
314            log("mS2.enter");
315        }
316        &#64;Override public boolean processMessage(Message message) {
317            boolean retVal;
318            log("mS2.processMessage what=" + message.what);
319            switch(message.what) {
320            case(CMD_2):
321                sendMessage(obtainMessage(CMD_4));
322                retVal = HANDLED;
323                break;
324            case(CMD_3):
325                deferMessage(message);
326                transitionTo(mP2);
327                retVal = HANDLED;
328                break;
329            default:
330                retVal = NOT_HANDLED;
331                break;
332            }
333            return retVal;
334        }
335        &#64;Override public void exit() {
336            log("mS2.exit");
337        }
338    }
339
340    class P2 extends State {
341        &#64;Override public void enter() {
342            log("mP2.enter");
343            sendMessage(obtainMessage(CMD_5));
344        }
345        &#64;Override public boolean processMessage(Message message) {
346            log("P2.processMessage what=" + message.what);
347            switch(message.what) {
348            case(CMD_3):
349                break;
350            case(CMD_4):
351                break;
352            case(CMD_5):
353                transitionToHaltingState();
354                break;
355            }
356            return HANDLED;
357        }
358        &#64;Override public void exit() {
359            log("mP2.exit");
360        }
361    }
362
363    &#64;Override
364    void onHalting() {
365        log("halting");
366        synchronized (this) {
367            this.notifyAll();
368        }
369    }
370
371    P1 mP1 = new P1();
372    S1 mS1 = new S1();
373    S2 mS2 = new S2();
374    P2 mP2 = new P2();
375}
376</code>
377 * <p>If this is executed by sending two messages CMD_1 and CMD_2
378 * (Note the synchronize is only needed because we use hsm.wait())</p>
379<code>
380Hsm1 hsm = makeHsm1();
381synchronize(hsm) {
382     hsm.sendMessage(obtainMessage(hsm.CMD_1));
383     hsm.sendMessage(obtainMessage(hsm.CMD_2));
384     try {
385          // wait for the messages to be handled
386          hsm.wait();
387     } catch (InterruptedException e) {
388          loge("exception while waiting " + e.getMessage());
389     }
390}
391</code>
392 * <p>The output is:</p>
393<code>
394D/hsm1    ( 1999): makeHsm1 E
395D/hsm1    ( 1999): ctor E
396D/hsm1    ( 1999): ctor X
397D/hsm1    ( 1999): mP1.enter
398D/hsm1    ( 1999): mS1.enter
399D/hsm1    ( 1999): makeHsm1 X
400D/hsm1    ( 1999): mS1.processMessage what=1
401D/hsm1    ( 1999): mS1.exit
402D/hsm1    ( 1999): mS1.enter
403D/hsm1    ( 1999): mS1.processMessage what=2
404D/hsm1    ( 1999): mP1.processMessage what=2
405D/hsm1    ( 1999): mS1.exit
406D/hsm1    ( 1999): mS2.enter
407D/hsm1    ( 1999): mS2.processMessage what=2
408D/hsm1    ( 1999): mS2.processMessage what=3
409D/hsm1    ( 1999): mS2.exit
410D/hsm1    ( 1999): mP1.exit
411D/hsm1    ( 1999): mP2.enter
412D/hsm1    ( 1999): mP2.processMessage what=3
413D/hsm1    ( 1999): mP2.processMessage what=4
414D/hsm1    ( 1999): mP2.processMessage what=5
415D/hsm1    ( 1999): mP2.exit
416D/hsm1    ( 1999): halting
417</code>
418 */
419public class StateMachine {
420    // Name of the state machine and used as logging tag
421    private String mName;
422
423    /** Message.what value when quitting */
424    private static final int SM_QUIT_CMD = -1;
425
426    /** Message.what value when initializing */
427    private static final int SM_INIT_CMD = -2;
428
429    /**
430     * Convenience constant that maybe returned by processMessage
431     * to indicate the the message was processed and is not to be
432     * processed by parent states
433     */
434    public static final boolean HANDLED = true;
435
436    /**
437     * Convenience constant that maybe returned by processMessage
438     * to indicate the the message was NOT processed and is to be
439     * processed by parent states
440     */
441    public static final boolean NOT_HANDLED = false;
442
443    /**
444     * StateMachine logging record.
445     * {@hide}
446     */
447    public static class LogRec {
448        private StateMachine mSm;
449        private long mTime;
450        private int mWhat;
451        private String mInfo;
452        private IState mState;
453        private IState mOrgState;
454        private IState mDstState;
455
456        /**
457         * Constructor
458         *
459         * @param msg
460         * @param state the state which handled the message
461         * @param orgState is the first state the received the message but
462         * did not processes the message.
463         * @param transToState is the state that was transitioned to after the message was
464         * processed.
465         */
466        LogRec(StateMachine sm, Message msg, String info, IState state, IState orgState,
467                IState transToState) {
468            update(sm, msg, info, state, orgState, transToState);
469        }
470
471        /**
472         * Update the information in the record.
473         * @param state that handled the message
474         * @param orgState is the first state the received the message
475         * @param dstState is the state that was the transition target when logging
476         */
477        public void update(StateMachine sm, Message msg, String info, IState state, IState orgState,
478                IState dstState) {
479            mSm = sm;
480            mTime = System.currentTimeMillis();
481            mWhat = (msg != null) ? msg.what : 0;
482            mInfo = info;
483            mState = state;
484            mOrgState = orgState;
485            mDstState = dstState;
486        }
487
488        /**
489         * @return time stamp
490         */
491        public long getTime() {
492            return mTime;
493        }
494
495        /**
496         * @return msg.what
497         */
498        public long getWhat() {
499            return mWhat;
500        }
501
502        /**
503         * @return the command that was executing
504         */
505        public String getInfo() {
506            return mInfo;
507        }
508
509        /**
510         * @return the state that handled this message
511         */
512        public IState getState() {
513            return mState;
514        }
515
516        /**
517         * @return the state destination state if a transition is occurring or null if none.
518         */
519        public IState getDestState() {
520            return mDstState;
521        }
522
523        /**
524         * @return the original state that received the message.
525         */
526        public IState getOriginalState() {
527            return mOrgState;
528        }
529
530        @Override
531        public String toString() {
532            StringBuilder sb = new StringBuilder();
533            sb.append("time=");
534            Calendar c = Calendar.getInstance();
535            c.setTimeInMillis(mTime);
536            sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
537            sb.append(" processed=");
538            sb.append(mState == null ? "<null>" : mState.getName());
539            sb.append(" org=");
540            sb.append(mOrgState == null ? "<null>" : mOrgState.getName());
541            sb.append(" dest=");
542            sb.append(mDstState == null ? "<null>" : mDstState.getName());
543            sb.append(" what=");
544            String what = mSm != null ? mSm.getWhatToString(mWhat) : "";
545            if (TextUtils.isEmpty(what)) {
546                sb.append(mWhat);
547                sb.append("(0x");
548                sb.append(Integer.toHexString(mWhat));
549                sb.append(")");
550            } else {
551                sb.append(what);
552            }
553            if (!TextUtils.isEmpty(mInfo)) {
554                sb.append(" ");
555                sb.append(mInfo);
556            }
557            return sb.toString();
558        }
559    }
560
561    /**
562     * A list of log records including messages recently processed by the state machine.
563     *
564     * The class maintains a list of log records including messages
565     * recently processed. The list is finite and may be set in the
566     * constructor or by calling setSize. The public interface also
567     * includes size which returns the number of recent records,
568     * count which is the number of records processed since the
569     * the last setSize, get which returns a record and
570     * add which adds a record.
571     */
572    private static class LogRecords {
573
574        private static final int DEFAULT_SIZE = 20;
575
576        private Vector<LogRec> mLogRecVector = new Vector<LogRec>();
577        private int mMaxSize = DEFAULT_SIZE;
578        private int mOldestIndex = 0;
579        private int mCount = 0;
580        private boolean mLogOnlyTransitions = false;
581
582        /**
583         * private constructor use add
584         */
585        private LogRecords() {
586        }
587
588        /**
589         * Set size of messages to maintain and clears all current records.
590         *
591         * @param maxSize number of records to maintain at anyone time.
592        */
593        synchronized void setSize(int maxSize) {
594            mMaxSize = maxSize;
595            mCount = 0;
596            mLogRecVector.clear();
597        }
598
599        synchronized void setLogOnlyTransitions(boolean enable) {
600            mLogOnlyTransitions = enable;
601        }
602
603        synchronized boolean logOnlyTransitions() {
604            return mLogOnlyTransitions;
605        }
606
607        /**
608         * @return the number of recent records.
609         */
610        synchronized int size() {
611            return mLogRecVector.size();
612        }
613
614        /**
615         * @return the total number of records processed since size was set.
616         */
617        synchronized int count() {
618            return mCount;
619        }
620
621        /**
622         * Clear the list of records.
623         */
624        synchronized void cleanup() {
625            mLogRecVector.clear();
626        }
627
628        /**
629         * @return the information on a particular record. 0 is the oldest
630         * record and size()-1 is the newest record. If the index is to
631         * large null is returned.
632         */
633        synchronized LogRec get(int index) {
634            int nextIndex = mOldestIndex + index;
635            if (nextIndex >= mMaxSize) {
636                nextIndex -= mMaxSize;
637            }
638            if (nextIndex >= size()) {
639                return null;
640            } else {
641                return mLogRecVector.get(nextIndex);
642            }
643        }
644
645        /**
646         * Add a processed message.
647         *
648         * @param msg
649         * @param messageInfo to be stored
650         * @param state that handled the message
651         * @param orgState is the first state the received the message but
652         * did not processes the message.
653         * @param transToState is the state that was transitioned to after the message was
654         * processed.
655         *
656         */
657        synchronized void add(StateMachine sm, Message msg, String messageInfo, IState state,
658                IState orgState, IState transToState) {
659            mCount += 1;
660            if (mLogRecVector.size() < mMaxSize) {
661                mLogRecVector.add(new LogRec(sm, msg, messageInfo, state, orgState, transToState));
662            } else {
663                LogRec pmi = mLogRecVector.get(mOldestIndex);
664                mOldestIndex += 1;
665                if (mOldestIndex >= mMaxSize) {
666                    mOldestIndex = 0;
667                }
668                pmi.update(sm, msg, messageInfo, state, orgState, transToState);
669            }
670        }
671    }
672
673    private static class SmHandler extends Handler {
674
675        /** The debug flag */
676        private boolean mDbg = false;
677
678        /** The SmHandler object, identifies that message is internal */
679        private static final Object mSmHandlerObj = new Object();
680
681        /** The current message */
682        private Message mMsg;
683
684        /** A list of log records including messages this state machine has processed */
685        private LogRecords mLogRecords = new LogRecords();
686
687        /** true if construction of the state machine has not been completed */
688        private boolean mIsConstructionCompleted;
689
690        /** Stack used to manage the current hierarchy of states */
691        private StateInfo mStateStack[];
692
693        /** Top of mStateStack */
694        private int mStateStackTopIndex = -1;
695
696        /** A temporary stack used to manage the state stack */
697        private StateInfo mTempStateStack[];
698
699        /** The top of the mTempStateStack */
700        private int mTempStateStackCount;
701
702        /** State used when state machine is halted */
703        private HaltingState mHaltingState = new HaltingState();
704
705        /** State used when state machine is quitting */
706        private QuittingState mQuittingState = new QuittingState();
707
708        /** Reference to the StateMachine */
709        private StateMachine mSm;
710
711        /**
712         * Information about a state.
713         * Used to maintain the hierarchy.
714         */
715        private class StateInfo {
716            /** The state */
717            State state;
718
719            /** The parent of this state, null if there is no parent */
720            StateInfo parentStateInfo;
721
722            /** True when the state has been entered and on the stack */
723            boolean active;
724
725            /**
726             * Convert StateInfo to string
727             */
728            @Override
729            public String toString() {
730                return "state=" + state.getName() + ",active=" + active + ",parent="
731                        + ((parentStateInfo == null) ? "null" : parentStateInfo.state.getName());
732            }
733        }
734
735        /** The map of all of the states in the state machine */
736        private HashMap<State, StateInfo> mStateInfo = new HashMap<State, StateInfo>();
737
738        /** The initial state that will process the first message */
739        private State mInitialState;
740
741        /** The destination state when transitionTo has been invoked */
742        private State mDestState;
743
744        /** The list of deferred messages */
745        private ArrayList<Message> mDeferredMessages = new ArrayList<Message>();
746
747        /**
748         * State entered when transitionToHaltingState is called.
749         */
750        private class HaltingState extends State {
751            @Override
752            public boolean processMessage(Message msg) {
753                mSm.haltedProcessMessage(msg);
754                return true;
755            }
756        }
757
758        /**
759         * State entered when a valid quit message is handled.
760         */
761        private class QuittingState extends State {
762            @Override
763            public boolean processMessage(Message msg) {
764                return NOT_HANDLED;
765            }
766        }
767
768        /**
769         * Handle messages sent to the state machine by calling
770         * the current state's processMessage. It also handles
771         * the enter/exit calls and placing any deferred messages
772         * back onto the queue when transitioning to a new state.
773         */
774        @Override
775        public final void handleMessage(Message msg) {
776            if (mDbg) mSm.log("handleMessage: E msg.what=" + msg.what);
777
778            /** Save the current message */
779            mMsg = msg;
780
781            /** State that processed the message */
782            State msgProcessedState = null;
783            if (mIsConstructionCompleted) {
784                /** Normal path */
785                msgProcessedState = processMsg(msg);
786            } else if (!mIsConstructionCompleted && (mMsg.what == SM_INIT_CMD)
787                    && (mMsg.obj == mSmHandlerObj)) {
788                /** Initial one time path. */
789                mIsConstructionCompleted = true;
790                invokeEnterMethods(0);
791            } else {
792                throw new RuntimeException("StateMachine.handleMessage: "
793                        + "The start method not called, received msg: " + msg);
794            }
795            performTransitions(msgProcessedState, msg);
796
797            // We need to check if mSm == null here as we could be quitting.
798            if (mDbg && mSm != null) mSm.log("handleMessage: X");
799        }
800
801        /**
802         * Do any transitions
803         * @param msgProcessedState is the state that processed the message
804         */
805        private void performTransitions(State msgProcessedState, Message msg) {
806            /**
807             * If transitionTo has been called, exit and then enter
808             * the appropriate states. We loop on this to allow
809             * enter and exit methods to use transitionTo.
810             */
811            State orgState = mStateStack[mStateStackTopIndex].state;
812
813            /**
814             * Record whether message needs to be logged before we transition and
815             * and we won't log special messages SM_INIT_CMD or SM_QUIT_CMD which
816             * always set msg.obj to the handler.
817             */
818            boolean recordLogMsg = mSm.recordLogRec(mMsg) && (msg.obj != mSmHandlerObj);
819
820            if (mLogRecords.logOnlyTransitions()) {
821                /** Record only if there is a transition */
822                if (mDestState != null) {
823                    mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState,
824                            orgState, mDestState);
825                }
826            } else if (recordLogMsg) {
827                /** Record message */
828                mLogRecords.add(mSm, mMsg, mSm.getLogRecString(mMsg), msgProcessedState, orgState,
829                        mDestState);
830            }
831
832            State destState = mDestState;
833            if (destState != null) {
834                /**
835                 * Process the transitions including transitions in the enter/exit methods
836                 */
837                while (true) {
838                    if (mDbg) mSm.log("handleMessage: new destination call exit/enter");
839
840                    /**
841                     * Determine the states to exit and enter and return the
842                     * common ancestor state of the enter/exit states. Then
843                     * invoke the exit methods then the enter methods.
844                     */
845                    StateInfo commonStateInfo = setupTempStateStackWithStatesToEnter(destState);
846                    invokeExitMethods(commonStateInfo);
847                    int stateStackEnteringIndex = moveTempStateStackToStateStack();
848                    invokeEnterMethods(stateStackEnteringIndex);
849
850                    /**
851                     * Since we have transitioned to a new state we need to have
852                     * any deferred messages moved to the front of the message queue
853                     * so they will be processed before any other messages in the
854                     * message queue.
855                     */
856                    moveDeferredMessageAtFrontOfQueue();
857
858                    if (destState != mDestState) {
859                        // A new mDestState so continue looping
860                        destState = mDestState;
861                    } else {
862                        // No change in mDestState so we're done
863                        break;
864                    }
865                }
866                mDestState = null;
867            }
868
869            /**
870             * After processing all transitions check and
871             * see if the last transition was to quit or halt.
872             */
873            if (destState != null) {
874                if (destState == mQuittingState) {
875                    /**
876                     * Call onQuitting to let subclasses cleanup.
877                     */
878                    mSm.onQuitting();
879                    cleanupAfterQuitting();
880                } else if (destState == mHaltingState) {
881                    /**
882                     * Call onHalting() if we've transitioned to the halting
883                     * state. All subsequent messages will be processed in
884                     * in the halting state which invokes haltedProcessMessage(msg);
885                     */
886                    mSm.onHalting();
887                }
888            }
889        }
890
891        /**
892         * Cleanup all the static variables and the looper after the SM has been quit.
893         */
894        private final void cleanupAfterQuitting() {
895            if (mSm.mSmThread != null) {
896                // If we made the thread then quit looper which stops the thread.
897                getLooper().quit();
898                mSm.mSmThread = null;
899            }
900
901            mSm.mSmHandler = null;
902            mSm = null;
903            mMsg = null;
904            mLogRecords.cleanup();
905            mStateStack = null;
906            mTempStateStack = null;
907            mStateInfo.clear();
908            mInitialState = null;
909            mDestState = null;
910            mDeferredMessages.clear();
911        }
912
913        /**
914         * Complete the construction of the state machine.
915         */
916        private final void completeConstruction() {
917            if (mDbg) mSm.log("completeConstruction: E");
918
919            /**
920             * Determine the maximum depth of the state hierarchy
921             * so we can allocate the state stacks.
922             */
923            int maxDepth = 0;
924            for (StateInfo si : mStateInfo.values()) {
925                int depth = 0;
926                for (StateInfo i = si; i != null; depth++) {
927                    i = i.parentStateInfo;
928                }
929                if (maxDepth < depth) {
930                    maxDepth = depth;
931                }
932            }
933            if (mDbg) mSm.log("completeConstruction: maxDepth=" + maxDepth);
934
935            mStateStack = new StateInfo[maxDepth];
936            mTempStateStack = new StateInfo[maxDepth];
937            setupInitialStateStack();
938
939            /** Sending SM_INIT_CMD message to invoke enter methods asynchronously */
940            sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD, mSmHandlerObj));
941
942            if (mDbg) mSm.log("completeConstruction: X");
943        }
944
945        /**
946         * Process the message. If the current state doesn't handle
947         * it, call the states parent and so on. If it is never handled then
948         * call the state machines unhandledMessage method.
949         * @return the state that processed the message
950         */
951        private final State processMsg(Message msg) {
952            StateInfo curStateInfo = mStateStack[mStateStackTopIndex];
953            if (mDbg) {
954                mSm.log("processMsg: " + curStateInfo.state.getName());
955            }
956
957            if (isQuit(msg)) {
958                transitionTo(mQuittingState);
959            } else {
960                while (!curStateInfo.state.processMessage(msg)) {
961                    /**
962                     * Not processed
963                     */
964                    curStateInfo = curStateInfo.parentStateInfo;
965                    if (curStateInfo == null) {
966                        /**
967                         * No parents left so it's not handled
968                         */
969                        mSm.unhandledMessage(msg);
970                        break;
971                    }
972                    if (mDbg) {
973                        mSm.log("processMsg: " + curStateInfo.state.getName());
974                    }
975                }
976            }
977            return (curStateInfo != null) ? curStateInfo.state : null;
978        }
979
980        /**
981         * Call the exit method for each state from the top of stack
982         * up to the common ancestor state.
983         */
984        private final void invokeExitMethods(StateInfo commonStateInfo) {
985            while ((mStateStackTopIndex >= 0)
986                    && (mStateStack[mStateStackTopIndex] != commonStateInfo)) {
987                State curState = mStateStack[mStateStackTopIndex].state;
988                if (mDbg) mSm.log("invokeExitMethods: " + curState.getName());
989                curState.exit();
990                mStateStack[mStateStackTopIndex].active = false;
991                mStateStackTopIndex -= 1;
992            }
993        }
994
995        /**
996         * Invoke the enter method starting at the entering index to top of state stack
997         */
998        private final void invokeEnterMethods(int stateStackEnteringIndex) {
999            for (int i = stateStackEnteringIndex; i <= mStateStackTopIndex; i++) {
1000                if (mDbg) mSm.log("invokeEnterMethods: " + mStateStack[i].state.getName());
1001                mStateStack[i].state.enter();
1002                mStateStack[i].active = true;
1003            }
1004        }
1005
1006        /**
1007         * Move the deferred message to the front of the message queue.
1008         */
1009        private final void moveDeferredMessageAtFrontOfQueue() {
1010            /**
1011             * The oldest messages on the deferred list must be at
1012             * the front of the queue so start at the back, which
1013             * as the most resent message and end with the oldest
1014             * messages at the front of the queue.
1015             */
1016            for (int i = mDeferredMessages.size() - 1; i >= 0; i--) {
1017                Message curMsg = mDeferredMessages.get(i);
1018                if (mDbg) mSm.log("moveDeferredMessageAtFrontOfQueue; what=" + curMsg.what);
1019                sendMessageAtFrontOfQueue(curMsg);
1020            }
1021            mDeferredMessages.clear();
1022        }
1023
1024        /**
1025         * Move the contents of the temporary stack to the state stack
1026         * reversing the order of the items on the temporary stack as
1027         * they are moved.
1028         *
1029         * @return index into mStateStack where entering needs to start
1030         */
1031        private final int moveTempStateStackToStateStack() {
1032            int startingIndex = mStateStackTopIndex + 1;
1033            int i = mTempStateStackCount - 1;
1034            int j = startingIndex;
1035            while (i >= 0) {
1036                if (mDbg) mSm.log("moveTempStackToStateStack: i=" + i + ",j=" + j);
1037                mStateStack[j] = mTempStateStack[i];
1038                j += 1;
1039                i -= 1;
1040            }
1041
1042            mStateStackTopIndex = j - 1;
1043            if (mDbg) {
1044                mSm.log("moveTempStackToStateStack: X mStateStackTop=" + mStateStackTopIndex
1045                        + ",startingIndex=" + startingIndex + ",Top="
1046                        + mStateStack[mStateStackTopIndex].state.getName());
1047            }
1048            return startingIndex;
1049        }
1050
1051        /**
1052         * Setup the mTempStateStack with the states we are going to enter.
1053         *
1054         * This is found by searching up the destState's ancestors for a
1055         * state that is already active i.e. StateInfo.active == true.
1056         * The destStae and all of its inactive parents will be on the
1057         * TempStateStack as the list of states to enter.
1058         *
1059         * @return StateInfo of the common ancestor for the destState and
1060         * current state or null if there is no common parent.
1061         */
1062        private final StateInfo setupTempStateStackWithStatesToEnter(State destState) {
1063            /**
1064             * Search up the parent list of the destination state for an active
1065             * state. Use a do while() loop as the destState must always be entered
1066             * even if it is active. This can happen if we are exiting/entering
1067             * the current state.
1068             */
1069            mTempStateStackCount = 0;
1070            StateInfo curStateInfo = mStateInfo.get(destState);
1071            do {
1072                mTempStateStack[mTempStateStackCount++] = curStateInfo;
1073                curStateInfo = curStateInfo.parentStateInfo;
1074            } while ((curStateInfo != null) && !curStateInfo.active);
1075
1076            if (mDbg) {
1077                mSm.log("setupTempStateStackWithStatesToEnter: X mTempStateStackCount="
1078                        + mTempStateStackCount + ",curStateInfo: " + curStateInfo);
1079            }
1080            return curStateInfo;
1081        }
1082
1083        /**
1084         * Initialize StateStack to mInitialState.
1085         */
1086        private final void setupInitialStateStack() {
1087            if (mDbg) {
1088                mSm.log("setupInitialStateStack: E mInitialState=" + mInitialState.getName());
1089            }
1090
1091            StateInfo curStateInfo = mStateInfo.get(mInitialState);
1092            for (mTempStateStackCount = 0; curStateInfo != null; mTempStateStackCount++) {
1093                mTempStateStack[mTempStateStackCount] = curStateInfo;
1094                curStateInfo = curStateInfo.parentStateInfo;
1095            }
1096
1097            // Empty the StateStack
1098            mStateStackTopIndex = -1;
1099
1100            moveTempStateStackToStateStack();
1101        }
1102
1103        /**
1104         * @return current message
1105         */
1106        private final Message getCurrentMessage() {
1107            return mMsg;
1108        }
1109
1110        /**
1111         * @return current state
1112         */
1113        private final IState getCurrentState() {
1114            return mStateStack[mStateStackTopIndex].state;
1115        }
1116
1117        /**
1118         * Add a new state to the state machine. Bottom up addition
1119         * of states is allowed but the same state may only exist
1120         * in one hierarchy.
1121         *
1122         * @param state the state to add
1123         * @param parent the parent of state
1124         * @return stateInfo for this state
1125         */
1126        private final StateInfo addState(State state, State parent) {
1127            if (mDbg) {
1128                mSm.log("addStateInternal: E state=" + state.getName() + ",parent="
1129                        + ((parent == null) ? "" : parent.getName()));
1130            }
1131            StateInfo parentStateInfo = null;
1132            if (parent != null) {
1133                parentStateInfo = mStateInfo.get(parent);
1134                if (parentStateInfo == null) {
1135                    // Recursively add our parent as it's not been added yet.
1136                    parentStateInfo = addState(parent, null);
1137                }
1138            }
1139            StateInfo stateInfo = mStateInfo.get(state);
1140            if (stateInfo == null) {
1141                stateInfo = new StateInfo();
1142                mStateInfo.put(state, stateInfo);
1143            }
1144
1145            // Validate that we aren't adding the same state in two different hierarchies.
1146            if ((stateInfo.parentStateInfo != null)
1147                    && (stateInfo.parentStateInfo != parentStateInfo)) {
1148                throw new RuntimeException("state already added");
1149            }
1150            stateInfo.state = state;
1151            stateInfo.parentStateInfo = parentStateInfo;
1152            stateInfo.active = false;
1153            if (mDbg) mSm.log("addStateInternal: X stateInfo: " + stateInfo);
1154            return stateInfo;
1155        }
1156
1157        /**
1158         * Constructor
1159         *
1160         * @param looper for dispatching messages
1161         * @param sm the hierarchical state machine
1162         */
1163        private SmHandler(Looper looper, StateMachine sm) {
1164            super(looper);
1165            mSm = sm;
1166
1167            addState(mHaltingState, null);
1168            addState(mQuittingState, null);
1169        }
1170
1171        /** @see StateMachine#setInitialState(State) */
1172        private final void setInitialState(State initialState) {
1173            if (mDbg) mSm.log("setInitialState: initialState=" + initialState.getName());
1174            mInitialState = initialState;
1175        }
1176
1177        /** @see StateMachine#transitionTo(IState) */
1178        private final void transitionTo(IState destState) {
1179            mDestState = (State) destState;
1180            if (mDbg) mSm.log("transitionTo: destState=" + mDestState.getName());
1181        }
1182
1183        /** @see StateMachine#deferMessage(Message) */
1184        private final void deferMessage(Message msg) {
1185            if (mDbg) mSm.log("deferMessage: msg=" + msg.what);
1186
1187            /* Copy the "msg" to "newMsg" as "msg" will be recycled */
1188            Message newMsg = obtainMessage();
1189            newMsg.copyFrom(msg);
1190
1191            mDeferredMessages.add(newMsg);
1192        }
1193
1194        /** @see StateMachine#quit() */
1195        private final void quit() {
1196            if (mDbg) mSm.log("quit:");
1197            sendMessage(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
1198        }
1199
1200        /** @see StateMachine#quitNow() */
1201        private final void quitNow() {
1202            if (mDbg) mSm.log("quitNow:");
1203            sendMessageAtFrontOfQueue(obtainMessage(SM_QUIT_CMD, mSmHandlerObj));
1204        }
1205
1206        /** Validate that the message was sent by quit or quitNow. */
1207        private final boolean isQuit(Message msg) {
1208            return (msg.what == SM_QUIT_CMD) && (msg.obj == mSmHandlerObj);
1209        }
1210
1211        /** @see StateMachine#isDbg() */
1212        private final boolean isDbg() {
1213            return mDbg;
1214        }
1215
1216        /** @see StateMachine#setDbg(boolean) */
1217        private final void setDbg(boolean dbg) {
1218            mDbg = dbg;
1219        }
1220
1221    }
1222
1223    private SmHandler mSmHandler;
1224    private HandlerThread mSmThread;
1225
1226    /**
1227     * Initialize.
1228     *
1229     * @param looper for this state machine
1230     * @param name of the state machine
1231     */
1232    private void initStateMachine(String name, Looper looper) {
1233        mName = name;
1234        mSmHandler = new SmHandler(looper, this);
1235    }
1236
1237    /**
1238     * Constructor creates a StateMachine with its own thread.
1239     *
1240     * @param name of the state machine
1241     */
1242    protected StateMachine(String name) {
1243        mSmThread = new HandlerThread(name);
1244        mSmThread.start();
1245        Looper looper = mSmThread.getLooper();
1246
1247        initStateMachine(name, looper);
1248    }
1249
1250    /**
1251     * Constructor creates a StateMachine using the looper.
1252     *
1253     * @param name of the state machine
1254     */
1255    protected StateMachine(String name, Looper looper) {
1256        initStateMachine(name, looper);
1257    }
1258
1259    /**
1260     * Add a new state to the state machine
1261     * @param state the state to add
1262     * @param parent the parent of state
1263     */
1264    protected final void addState(State state, State parent) {
1265        mSmHandler.addState(state, parent);
1266    }
1267
1268    /**
1269     * Add a new state to the state machine, parent will be null
1270     * @param state to add
1271     */
1272    protected final void addState(State state) {
1273        mSmHandler.addState(state, null);
1274    }
1275
1276    /**
1277     * Set the initial state. This must be invoked before
1278     * and messages are sent to the state machine.
1279     *
1280     * @param initialState is the state which will receive the first message.
1281     */
1282    protected final void setInitialState(State initialState) {
1283        mSmHandler.setInitialState(initialState);
1284    }
1285
1286    /**
1287     * @return current message
1288     */
1289    protected final Message getCurrentMessage() {
1290        // mSmHandler can be null if the state machine has quit.
1291        SmHandler smh = mSmHandler;
1292        if (smh == null) return null;
1293        return smh.getCurrentMessage();
1294    }
1295
1296    /**
1297     * @return current state
1298     */
1299    protected final IState getCurrentState() {
1300        // mSmHandler can be null if the state machine has quit.
1301        SmHandler smh = mSmHandler;
1302        if (smh == null) return null;
1303        return smh.getCurrentState();
1304    }
1305
1306    /**
1307     * transition to destination state. Upon returning
1308     * from processMessage the current state's exit will
1309     * be executed and upon the next message arriving
1310     * destState.enter will be invoked.
1311     *
1312     * this function can also be called inside the enter function of the
1313     * previous transition target, but the behavior is undefined when it is
1314     * called mid-way through a previous transition (for example, calling this
1315     * in the enter() routine of a intermediate node when the current transition
1316     * target is one of the nodes descendants).
1317     *
1318     * @param destState will be the state that receives the next message.
1319     */
1320    protected final void transitionTo(IState destState) {
1321        mSmHandler.transitionTo(destState);
1322    }
1323
1324    /**
1325     * transition to halt state. Upon returning
1326     * from processMessage we will exit all current
1327     * states, execute the onHalting() method and then
1328     * for all subsequent messages haltedProcessMessage
1329     * will be called.
1330     */
1331    protected final void transitionToHaltingState() {
1332        mSmHandler.transitionTo(mSmHandler.mHaltingState);
1333    }
1334
1335    /**
1336     * Defer this message until next state transition.
1337     * Upon transitioning all deferred messages will be
1338     * placed on the queue and reprocessed in the original
1339     * order. (i.e. The next state the oldest messages will
1340     * be processed first)
1341     *
1342     * @param msg is deferred until the next transition.
1343     */
1344    protected final void deferMessage(Message msg) {
1345        mSmHandler.deferMessage(msg);
1346    }
1347
1348    /**
1349     * Called when message wasn't handled
1350     *
1351     * @param msg that couldn't be handled.
1352     */
1353    protected void unhandledMessage(Message msg) {
1354        if (mSmHandler.mDbg) loge(" - unhandledMessage: msg.what=" + msg.what);
1355    }
1356
1357    /**
1358     * Called for any message that is received after
1359     * transitionToHalting is called.
1360     */
1361    protected void haltedProcessMessage(Message msg) {
1362    }
1363
1364    /**
1365     * This will be called once after handling a message that called
1366     * transitionToHalting. All subsequent messages will invoke
1367     * {@link StateMachine#haltedProcessMessage(Message)}
1368     */
1369    protected void onHalting() {
1370    }
1371
1372    /**
1373     * This will be called once after a quit message that was NOT handled by
1374     * the derived StateMachine. The StateMachine will stop and any subsequent messages will be
1375     * ignored. In addition, if this StateMachine created the thread, the thread will
1376     * be stopped after this method returns.
1377     */
1378    protected void onQuitting() {
1379    }
1380
1381    /**
1382     * @return the name
1383     */
1384    public final String getName() {
1385        return mName;
1386    }
1387
1388    /**
1389     * Set number of log records to maintain and clears all current records.
1390     *
1391     * @param maxSize number of messages to maintain at anyone time.
1392     */
1393    public final void setLogRecSize(int maxSize) {
1394        mSmHandler.mLogRecords.setSize(maxSize);
1395    }
1396
1397    /**
1398     * Set to log only messages that cause a state transition
1399     *
1400     * @param enable {@code true} to enable, {@code false} to disable
1401     */
1402    public final void setLogOnlyTransitions(boolean enable) {
1403        mSmHandler.mLogRecords.setLogOnlyTransitions(enable);
1404    }
1405
1406    /**
1407     * @return number of log records
1408     */
1409    public final int getLogRecSize() {
1410        // mSmHandler can be null if the state machine has quit.
1411        SmHandler smh = mSmHandler;
1412        if (smh == null) return 0;
1413        return smh.mLogRecords.size();
1414    }
1415
1416    /**
1417     * @return the total number of records processed
1418     */
1419    public final int getLogRecCount() {
1420        // mSmHandler can be null if the state machine has quit.
1421        SmHandler smh = mSmHandler;
1422        if (smh == null) return 0;
1423        return smh.mLogRecords.count();
1424    }
1425
1426    /**
1427     * @return a log record, or null if index is out of range
1428     */
1429    public final LogRec getLogRec(int index) {
1430        // mSmHandler can be null if the state machine has quit.
1431        SmHandler smh = mSmHandler;
1432        if (smh == null) return null;
1433        return smh.mLogRecords.get(index);
1434    }
1435
1436    /**
1437     * @return a copy of LogRecs as a collection
1438     */
1439    public final Collection<LogRec> copyLogRecs() {
1440        Vector<LogRec> vlr = new Vector<LogRec>();
1441        SmHandler smh = mSmHandler;
1442        if (smh != null) {
1443            for (LogRec lr : smh.mLogRecords.mLogRecVector) {
1444                vlr.add(lr);
1445            }
1446        }
1447        return vlr;
1448    }
1449
1450    /**
1451     * Add the string to LogRecords.
1452     *
1453     * @param string
1454     */
1455    protected void addLogRec(String string) {
1456        // mSmHandler can be null if the state machine has quit.
1457        SmHandler smh = mSmHandler;
1458        if (smh == null) return;
1459        smh.mLogRecords.add(this, smh.getCurrentMessage(), string, smh.getCurrentState(),
1460                smh.mStateStack[smh.mStateStackTopIndex].state, smh.mDestState);
1461    }
1462
1463    /**
1464     * @return true if msg should be saved in the log, default is true.
1465     */
1466    protected boolean recordLogRec(Message msg) {
1467        return true;
1468    }
1469
1470    /**
1471     * Return a string to be logged by LogRec, default
1472     * is an empty string. Override if additional information is desired.
1473     *
1474     * @param msg that was processed
1475     * @return information to be logged as a String
1476     */
1477    protected String getLogRecString(Message msg) {
1478        return "";
1479    }
1480
1481    /**
1482     * @return the string for msg.what
1483     */
1484    protected String getWhatToString(int what) {
1485        return null;
1486    }
1487
1488    /**
1489     * @return Handler, maybe null if state machine has quit.
1490     */
1491    public final Handler getHandler() {
1492        return mSmHandler;
1493    }
1494
1495    /**
1496     * Get a message and set Message.target state machine handler.
1497     *
1498     * Note: The handler can be null if the state machine has quit,
1499     * which means target will be null and may cause a AndroidRuntimeException
1500     * in MessageQueue#enqueMessage if sent directly or if sent using
1501     * StateMachine#sendMessage the message will just be ignored.
1502     *
1503     * @return  A Message object from the global pool
1504     */
1505    public final Message obtainMessage() {
1506        return Message.obtain(mSmHandler);
1507    }
1508
1509    /**
1510     * Get a message and set Message.target state machine handler, what.
1511     *
1512     * Note: The handler can be null if the state machine has quit,
1513     * which means target will be null and may cause a AndroidRuntimeException
1514     * in MessageQueue#enqueMessage if sent directly or if sent using
1515     * StateMachine#sendMessage the message will just be ignored.
1516     *
1517     * @param what is the assigned to Message.what.
1518     * @return  A Message object from the global pool
1519     */
1520    public final Message obtainMessage(int what) {
1521        return Message.obtain(mSmHandler, what);
1522    }
1523
1524    /**
1525     * Get a message and set Message.target state machine handler,
1526     * what and obj.
1527     *
1528     * Note: The handler can be null if the state machine has quit,
1529     * which means target will be null and may cause a AndroidRuntimeException
1530     * in MessageQueue#enqueMessage if sent directly or if sent using
1531     * StateMachine#sendMessage the message will just be ignored.
1532     *
1533     * @param what is the assigned to Message.what.
1534     * @param obj is assigned to Message.obj.
1535     * @return  A Message object from the global pool
1536     */
1537    public final Message obtainMessage(int what, Object obj) {
1538        return Message.obtain(mSmHandler, what, obj);
1539    }
1540
1541    /**
1542     * Get a message and set Message.target state machine handler,
1543     * what, arg1 and arg2
1544     *
1545     * Note: The handler can be null if the state machine has quit,
1546     * which means target will be null and may cause a AndroidRuntimeException
1547     * in MessageQueue#enqueMessage if sent directly or if sent using
1548     * StateMachine#sendMessage the message will just be ignored.
1549     *
1550     * @param what  is assigned to Message.what
1551     * @param arg1  is assigned to Message.arg1
1552     * @param arg2  is assigned to Message.arg2
1553     * @return  A Message object from the global pool
1554     */
1555    public final Message obtainMessage(int what, int arg1, int arg2) {
1556        return Message.obtain(mSmHandler, what, arg1, arg2);
1557    }
1558
1559    /**
1560     * Get a message and set Message.target state machine handler,
1561     * what, arg1, arg2 and obj
1562     *
1563     * Note: The handler can be null if the state machine has quit,
1564     * which means target will be null and may cause a AndroidRuntimeException
1565     * in MessageQueue#enqueMessage if sent directly or if sent using
1566     * StateMachine#sendMessage the message will just be ignored.
1567     *
1568     * @param what  is assigned to Message.what
1569     * @param arg1  is assigned to Message.arg1
1570     * @param arg2  is assigned to Message.arg2
1571     * @param obj is assigned to Message.obj
1572     * @return  A Message object from the global pool
1573     */
1574    public final Message obtainMessage(int what, int arg1, int arg2, Object obj) {
1575        return Message.obtain(mSmHandler, what, arg1, arg2, obj);
1576    }
1577
1578    /**
1579     * Enqueue a message to this state machine.
1580     *
1581     * Message is ignored if state machine has quit.
1582     */
1583    public final void sendMessage(int what) {
1584        // mSmHandler can be null if the state machine has quit.
1585        SmHandler smh = mSmHandler;
1586        if (smh == null) return;
1587
1588        smh.sendMessage(obtainMessage(what));
1589    }
1590
1591    /**
1592     * Enqueue a message to this state machine.
1593     *
1594     * Message is ignored if state machine has quit.
1595     */
1596    public final void sendMessage(int what, Object obj) {
1597        // mSmHandler can be null if the state machine has quit.
1598        SmHandler smh = mSmHandler;
1599        if (smh == null) return;
1600
1601        smh.sendMessage(obtainMessage(what, obj));
1602    }
1603
1604    /**
1605     * Enqueue a message to this state machine.
1606     *
1607     * Message is ignored if state machine has quit.
1608     */
1609    public final void sendMessage(Message msg) {
1610        // mSmHandler can be null if the state machine has quit.
1611        SmHandler smh = mSmHandler;
1612        if (smh == null) return;
1613
1614        smh.sendMessage(msg);
1615    }
1616
1617    /**
1618     * Enqueue a message to this state machine after a delay.
1619     *
1620     * Message is ignored if state machine has quit.
1621     */
1622    public final void sendMessageDelayed(int what, long delayMillis) {
1623        // mSmHandler can be null if the state machine has quit.
1624        SmHandler smh = mSmHandler;
1625        if (smh == null) return;
1626
1627        smh.sendMessageDelayed(obtainMessage(what), delayMillis);
1628    }
1629
1630    /**
1631     * Enqueue a message to this state machine after a delay.
1632     *
1633     * Message is ignored if state machine has quit.
1634     */
1635    public final void sendMessageDelayed(int what, Object obj, long delayMillis) {
1636        // mSmHandler can be null if the state machine has quit.
1637        SmHandler smh = mSmHandler;
1638        if (smh == null) return;
1639
1640        smh.sendMessageDelayed(obtainMessage(what, obj), delayMillis);
1641    }
1642
1643    /**
1644     * Enqueue a message to this state machine after a delay.
1645     *
1646     * Message is ignored if state machine has quit.
1647     */
1648    public final void sendMessageDelayed(Message msg, long delayMillis) {
1649        // mSmHandler can be null if the state machine has quit.
1650        SmHandler smh = mSmHandler;
1651        if (smh == null) return;
1652
1653        smh.sendMessageDelayed(msg, delayMillis);
1654    }
1655
1656    /**
1657     * Enqueue a message to the front of the queue for this state machine.
1658     * Protected, may only be called by instances of StateMachine.
1659     *
1660     * Message is ignored if state machine has quit.
1661     */
1662    protected final void sendMessageAtFrontOfQueue(int what, Object obj) {
1663        // mSmHandler can be null if the state machine has quit.
1664        SmHandler smh = mSmHandler;
1665        if (smh == null) return;
1666
1667        smh.sendMessageAtFrontOfQueue(obtainMessage(what, obj));
1668    }
1669
1670    /**
1671     * Enqueue a message to the front of the queue for this state machine.
1672     * Protected, may only be called by instances of StateMachine.
1673     *
1674     * Message is ignored if state machine has quit.
1675     */
1676    protected final void sendMessageAtFrontOfQueue(int what) {
1677        // mSmHandler can be null if the state machine has quit.
1678        SmHandler smh = mSmHandler;
1679        if (smh == null) return;
1680
1681        smh.sendMessageAtFrontOfQueue(obtainMessage(what));
1682    }
1683
1684    /**
1685     * Enqueue a message to the front of the queue for this state machine.
1686     * Protected, may only be called by instances of StateMachine.
1687     *
1688     * Message is ignored if state machine has quit.
1689     */
1690    protected final void sendMessageAtFrontOfQueue(Message msg) {
1691        // mSmHandler can be null if the state machine has quit.
1692        SmHandler smh = mSmHandler;
1693        if (smh == null) return;
1694
1695        smh.sendMessageAtFrontOfQueue(msg);
1696    }
1697
1698    /**
1699     * Removes a message from the message queue.
1700     * Protected, may only be called by instances of StateMachine.
1701     */
1702    protected final void removeMessages(int what) {
1703        // mSmHandler can be null if the state machine has quit.
1704        SmHandler smh = mSmHandler;
1705        if (smh == null) return;
1706
1707        smh.removeMessages(what);
1708    }
1709
1710    /**
1711     * Validate that the message was sent by
1712     * {@link StateMachine#quit} or {@link StateMachine#quitNow}.
1713     * */
1714    protected final boolean isQuit(Message msg) {
1715        // mSmHandler can be null if the state machine has quit.
1716        SmHandler smh = mSmHandler;
1717        if (smh == null) return msg.what == SM_QUIT_CMD;
1718
1719        return smh.isQuit(msg);
1720    }
1721
1722    /**
1723     * Quit the state machine after all currently queued up messages are processed.
1724     */
1725    protected final void quit() {
1726        // mSmHandler can be null if the state machine is already stopped.
1727        SmHandler smh = mSmHandler;
1728        if (smh == null) return;
1729
1730        smh.quit();
1731    }
1732
1733    /**
1734     * Quit the state machine immediately all currently queued messages will be discarded.
1735     */
1736    protected final void quitNow() {
1737        // mSmHandler can be null if the state machine is already stopped.
1738        SmHandler smh = mSmHandler;
1739        if (smh == null) return;
1740
1741        smh.quitNow();
1742    }
1743
1744    /**
1745     * @return if debugging is enabled
1746     */
1747    public boolean isDbg() {
1748        // mSmHandler can be null if the state machine has quit.
1749        SmHandler smh = mSmHandler;
1750        if (smh == null) return false;
1751
1752        return smh.isDbg();
1753    }
1754
1755    /**
1756     * Set debug enable/disabled.
1757     *
1758     * @param dbg is true to enable debugging.
1759     */
1760    public void setDbg(boolean dbg) {
1761        // mSmHandler can be null if the state machine has quit.
1762        SmHandler smh = mSmHandler;
1763        if (smh == null) return;
1764
1765        smh.setDbg(dbg);
1766    }
1767
1768    /**
1769     * Start the state machine.
1770     */
1771    public void start() {
1772        // mSmHandler can be null if the state machine has quit.
1773        SmHandler smh = mSmHandler;
1774        if (smh == null) return;
1775
1776        /** Send the complete construction message */
1777        smh.completeConstruction();
1778    }
1779
1780    /**
1781     * Dump the current state.
1782     *
1783     * @param fd
1784     * @param pw
1785     * @param args
1786     */
1787    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1788        pw.println(getName() + ":");
1789        pw.println(" total records=" + getLogRecCount());
1790        for (int i = 0; i < getLogRecSize(); i++) {
1791            pw.printf(" rec[%d]: %s\n", i, getLogRec(i).toString());
1792            pw.flush();
1793        }
1794        pw.println("curState=" + getCurrentState().getName());
1795    }
1796
1797    /**
1798     * Log with debug and add to the LogRecords.
1799     *
1800     * @param s is string log
1801     */
1802    protected void logAndAddLogRec(String s) {
1803        addLogRec(s);
1804        log(s);
1805    }
1806
1807    /**
1808     * Log with debug
1809     *
1810     * @param s is string log
1811     */
1812    protected void log(String s) {
1813        Log.d(mName, s);
1814    }
1815
1816    /**
1817     * Log with debug attribute
1818     *
1819     * @param s is string log
1820     */
1821    protected void logd(String s) {
1822        Log.d(mName, s);
1823    }
1824
1825    /**
1826     * Log with verbose attribute
1827     *
1828     * @param s is string log
1829     */
1830    protected void logv(String s) {
1831        Log.v(mName, s);
1832    }
1833
1834    /**
1835     * Log with info attribute
1836     *
1837     * @param s is string log
1838     */
1839    protected void logi(String s) {
1840        Log.i(mName, s);
1841    }
1842
1843    /**
1844     * Log with warning attribute
1845     *
1846     * @param s is string log
1847     */
1848    protected void logw(String s) {
1849        Log.w(mName, s);
1850    }
1851
1852    /**
1853     * Log with error attribute
1854     *
1855     * @param s is string log
1856     */
1857    protected void loge(String s) {
1858        Log.e(mName, s);
1859    }
1860
1861    /**
1862     * Log with error attribute
1863     *
1864     * @param s is string log
1865     * @param e is a Throwable which logs additional information.
1866     */
1867    protected void loge(String s, Throwable e) {
1868        Log.e(mName, s, e);
1869    }
1870}
1871