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