android StateMachine.java

原创 2015年11月18日 23:30:23

android 4.0.4: /frameworks/base/core/java/com/android/internal/util/StateMachine.java

StateMachine状态机中,会创建HandlerThread线程,和依附该线程的Handler;消息处理都是在HandlerThread中执行

framework层的好几个状态机,都是在StateMachine基础上实现的,比如:WifiStateMachine、DhcpStateMachine、WifiWatchdogStateMachine。。。

http://androidxref.com/4.0.4/xref/frameworks/base/core/java/com/android/internal/util/StateMachine.java

SmHandler:

       /**
         * Handle messages sent to the state machine by calling
         * the current state's processMessage. It also handles
         * the enter/exit calls and placing any deferred messages
         * back onto the queue when transitioning to a new state.
         */
        @Override
        public final void handleMessage(Message msg) {
            if (mDbg) Log.d(TAG, "handleMessage: E msg.what=" + msg.what);

            /** Save the current message */
            mMsg = msg;

            /**
             * Check that construction was completed
             */
            if (!mIsConstructionCompleted) {
                Log.e(TAG, "The start method not called, ignore msg: " + msg);//  在状态机没有启动之前,收到msg,只是打印error日志
                return;
            }


            /**
             * Process the message abiding by the hierarchical semantics
             * and perform any requested transitions.
             */
            processMsg(msg);
            performTransitions();

            if (mDbg) Log.d(TAG, "handleMessage: X");
        }


        /**
         * Complete the construction of the state machine.
         */
        private final void completeConstruction() {
            if (mDbg) Log.d(TAG, "completeConstruction: E");

            /**
             * Determine the maximum depth of the state hierarchy
             * so we can allocate the state stacks.
             */
            int maxDepth = 0;
            for (StateInfo si : mStateInfo.values()) {
                int depth = 0;
                for (StateInfo i = si; i != null; depth++) {
                    i = i.parentStateInfo;
                }
                if (maxDepth < depth) {
                    maxDepth = depth;
                }
            }
            if (mDbg) Log.d(TAG, "completeConstruction: maxDepth=" + maxDepth);

            mStateStack = new StateInfo[maxDepth];
            mTempStateStack = new StateInfo[maxDepth];
            setupInitialStateStack();

            /**
             * Construction is complete call all enter methods
             * starting at the first entry.
             */
            mIsConstructionCompleted = true;
            mMsg = obtainMessage(SM_INIT_CMD);
            invokeEnterMethods(0);// 初始状态的enter方法,在调用线程中执行;即如果在UI线程中,调用状态机的start()方法,则初始状态的enter方法,在UI线程中执行,如果enter方法中有耗时的操作,肯定会占用UI线程的资源

            /**
             * Perform any transitions requested by the enter methods
             */
            performTransitions();// 如果初始状态的enter方法中,有跳转,即调用了transitionTo方法,则初始状态的exit方法、新状态的enter方法,也都会在调用线程中执行,依次类推,也会进一步占用调用线程的资源

            if (mDbg) Log.d(TAG, "completeConstruction: X");
        }

StateMachine:

    /**
     * Start the state machine.
     */
    public void start() {
        // mSmHandler can be null if the state machine has quit.
        if (mSmHandler == null) return;

        /** Send the complete construction message */
        mSmHandler.completeConstruction();
    }

///////////////////////////////////////////////////////////////////////////////////////////////////////////     

android 4.1.1: /frameworks/base/core/java/com/android/internal/util/StateMachine.java

http://androidxref.com/4.1.1/xref/frameworks/base/core/java/com/android/internal/util/StateMachine.java

SmHandler:

        /**
         * Handle messages sent to the state machine by calling
         * the current state's processMessage. It also handles
         * the enter/exit calls and placing any deferred messages
         * back onto the queue when transitioning to a new state.
         */
        @Override
        public final void handleMessage(Message msg) {
            if (mDbg) Log.d(TAG, "handleMessage: E msg.what=" + msg.what);

            /** Save the current message */
            mMsg = msg;

            if (mIsConstructionCompleted) {
                /** Normal path */
                processMsg(msg);
            } else if (!mIsConstructionCompleted && (mMsg.what == SM_INIT_CMD) && (mMsg.obj == mSmHandlerObj)) {
                /** Initial one time path. */
                mIsConstructionCompleted = true;// 调用start方法,走该分支一次;后面处理消息,都走前面的分支processMsg;(在HandlerThread线程中执行)
                invokeEnterMethods(0);

            } else {
                throw new RuntimeException("StateMachine.handleMessage: " + "The start method not called, received msg: " + msg);//  这里也是修改点,状态机没有启动之前,即没有调用start()方法之前,在4.0.4上,是打印error日志;在4.1.1上,则是
            }
            performTransitions();

            if (mDbg) Log.d(TAG, "handleMessage: X");
        }


        /**
         * Complete the construction of the state machine.
         */
        private final void completeConstruction() {
            if (mDbg) Log.d(TAG, "completeConstruction: E");

            /**
             * Determine the maximum depth of the state hierarchy
             * so we can allocate the state stacks.
             */
            int maxDepth = 0;
            for (StateInfo si : mStateInfo.values()) {
                int depth = 0;
                for (StateInfo i = si; i != null; depth++) {
                    i = i.parentStateInfo;
                }
                if (maxDepth < depth) {
                    maxDepth = depth;
                }
            }
            if (mDbg) Log.d(TAG, "completeConstruction: maxDepth=" + maxDepth);

            mStateStack = new StateInfo[maxDepth];
            mTempStateStack = new StateInfo[maxDepth];
            setupInitialStateStack();

            /** Sending SM_INIT_CMD message to invoke enter methods asynchronously */
            sendMessageAtFrontOfQueue(obtainMessage(SM_INIT_CMD, mSmHandlerObj));// 不同于4.0.4,比如:在UI线程中,调用状态机的start方法,这里只是把SM_INIT_CMD消息发送给HandlerThread中的Handler处理,初始状态的enter、exit方法,都是在状态机的HandlerThread线程中执行的,不会占用UI线程的资源^-^算是一个小改进吧


            if (mDbg) Log.d(TAG, "completeConstruction: X");
        }

StateMachine:

    /**
     * Enqueue a message to the front of the queue for this state machine.
     * Protected, may only be called by instances of StateMachine.
     */
    protected final void sendMessageAtFrontOfQueue(int what, Object obj) {
        mSmHandler.sendMessageAtFrontOfQueue(obtainMessage(what, obj));
    }

Android蓝牙源码分析——StateMachine状态机

StateMachine有自己单独的工作线程,protected StateMachine(String name) { mSmThread = new HandlerThread(name)...

Android -- StateMachine解析

Android -- StateMachine

Android StateMachine 学习笔记

通过阅读Google代码文档来学习 StateMachine 其实Google的代码文档对StateMachine介绍已经很详细了,详细阅读之后所了解的东西,完全可以应付使用。 首先先贴出StateM...

Android StateMachine和AsyncChannel

在学习Android Wifi的code时,到处可以看到StateMachie和AsyncChannel的影子,这里我们先大致分析一下它们两个的原理。 StateMachine原理分析 ...

Android StateMachine 总结

StateMachine类是用于管理机器的多种状态的机制。机器的每种状态由继承State类来表示。...

Android学习 StateMachine与State模式

Android学习 StateMachine与State模式 一 State模式 意图:   允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。(Objects for S...
  • myxmu
  • myxmu
  • 2012年08月28日 19:25
  • 773

Android StateMachine实践

我们在实际应用中经常遇到状态设计模式,Android 框架中给我们提供了一个经典的状态模式实现——StateMachine。在StateMachine之前,先来看下状态设计模式定义和UML类图。 状态...
  • chewbee
  • chewbee
  • 2017年05月25日 22:17
  • 118

Android wifi-framework StateMachine和AsyncChannel 学习

android中,wifi的核心是WPAS(wpa_supplicant),它管理和控制Android平台中的Wi-Fi功能。在整个wifi模块中,其更像是一个一个服务端,实现了连接,认证等工作流程。...
  • myvest
  • myvest
  • 2017年07月20日 14:25
  • 300

android状态机statemachine详解

先说两句题外话,很感谢android,在这里能看到很多优秀的代码。同时也感觉到外面的工程师真的很厉害,都是java人家就能写出这么牛的东西。感慨之下就有了些思考:我们绝大多数人只要把那些牛人已经创造出...
  • ts1122
  • ts1122
  • 2013年08月13日 07:18
  • 6640

Android StateMachine与State模式

原文地址:http://www.cnblogs.com/bastard/archive/2012/06/05/2536258.html                   Android Sta...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:android StateMachine.java
举报原因:
原因补充:

(最多只允许输入30个字)