Android StateMachine

一、Android StateMachine介绍

Android 状态机的主要作用是管理状态和处理消息。它通过定义一组状态和状态之间的转换关系,来控制系统的行为。当系统接收到消息时,StateMachine会根据当前的状态和消息类型,执行相应的操作或状态转换。

在使用Android 状态时,通常需要定义一组状态和状态之间的转换关系。可以使用addState()方法来添加状态,并使用addTransition()方法来定义状态之间的转换关系。当系统接收到消息时,可以使用sendMessage()方法将消息发送给StateMachine,并由StateMachine根据当前的状态和消息类型来执行相应的操作。

  1. StateMachine的概念: StateMachine是一种用于管理和处理状态转换的机制。它由一组状态和状态之间的转换组成。每个状态都有与之关联的操作和事件。当发生特定的事件时,StateMachine会根据当前状态和事件触发相应的操作,并根据定义的转换规则切换到新的状态。

  2. StateMachine的使用: 在Android中,StateMachine是通过继承android.os.Handler类来实现的。开发者可以创建自定义的StateMachine类,并在其中定义状态、事件和操作。通过重写handleMessage()方法来处理不同的事件,并在其中执行相应的操作和状态转换。

  3. StateMachine的示例代码: 下面是一个简单的示例代码,演示了如何使用StateMachine来管理和处理状态转换:

public class MyStateMachine extends StateMachine {
    private static final int MSG_HELLO = 1;


    private State mStateA = new StateA();
    private State mStateB = new StateB();


    public MyStateMachine() {
        super("MyStateMachine");


        addState(mStateA);
        addState(mStateB);
        setInitialState(mStateA);
    }


    private class StateA extends State {
        @Override
        public boolean processMessage(Message msg) {
            switch (msg.what) {
                case MSG_HELLO:
                    // 处理消息
                    Log.d("MyStateMachine", "Hello from State A");
                    // 状态转换
                    transitionTo(mStateB);
                    return true;
                default:
                    return false;
            }
        }
    }


    private class StateB extends State {
        @Override
        public boolean processMessage(Message msg) {
            switch (msg.what) {
                case MSG_HELLO:
                    // 处理消息
                    Log.d("MyStateMachine", "Hello from State B");
                    // 状态转换
                    transitionTo(mStateA);
                    return true;
                default:
                    return false;
            }
        }
    }
}

在上面的示例中,我们创建了一个名为MyStateMachine的自定义StateMachine类。它有三个状态:STATE_IDLE、STATE_RUNNING和STATE_FINISHED。在handleMessage()方法中,我们根据当前状态和接收到的事件来执行相应的操作和状态转换。

二、Android状态机相关类和接口

Android状态机相关类图如下:

StateMachine

Android StateMachine是Android框架中的一个类,用于管理状态和处理消息。它是一个有限状态机(Finite State Machine),用于在Android系统中实现状态转换和消息处理的机制。

StateMachine状态机,有三个内部类LogRec、LogRecords、SmHandler,其中LogRec和LogRecords为日志相关,SmHandler为StateMachine核心类。

SmHandler内部还包括三个内部类StateInfo 、HaltingState 、QuittingState ,其中StateInfo用于存储当前State,和其parentState,以及是否激活状态;用来构建树形层次结构模型。HaltingState与QuittingState都是State的 派生类,用于在状态停止和放弃之后处理的一些事情;都重写了ProcessMessage方法,在StateMachine没有实际行动仅仅保留用于扩展。

整个SmHandle是消息处理派发和状态控制切换的核心,运行在单独的线程上。SmHandle是构建StateMachine的核心,运行在独立的线程上,有三个功能:

1、建立树形层次结构存储State;

2、状态机的StateStack建立和状态切换;

3、消息处理和派发;

StateMachine文件路径:

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

StateMachine定义:

public class StateMachine {
    public static class LogRec {} //StateMachine 日志记录。
    private static class LogRecords {} //日志记录列表,包括状态机最近处理的消息。
    private static class SmHandler extends Handler { //状态机处理
    private class HaltingState extends State { //停止状态
    public boolean processMessage(Message msg) {} //调用 transitionToHaltingState 时输入的状态。
    }
    private class QuittingState extends State { //退出状态
    public boolean processMessage(Message msg) {} //处理有效退出消息时输入的状态。
    }
    public final void handleMessage(Message msg) {} //通过调用当前状态的 processMessage 来处理发送到状态机的消息。
    }
}

StateMachine 方法:

public final void addState(State state, State parent) :Add a new state to the state machine.
public final void addState(State state) :Add a new state to the state machine, parent will be null.
public final void removeState(State state):Removes a state from the state machine, unless it is currently active or if it has children.
public final void setInitialState(State initialState):Set the initial state. This must be invoked before and messages are sent to the state machine.
public final Message getCurrentMessage() :return current message.
public final IState getCurrentState():return current state.
public final void transitionTo(IState destState):transition to destination state.
public final void transitionToHaltingState():transition to halt state. 
public final void deferMessage(Message msg) :Defer this message until next state transition.
public final String getName():return the name.
public final void setLogRecSize(int maxSize) :Set number of log records to maintain and clears all current records.
public final void setLogRecSize(int maxSize):Set number of log records to maintain and clears all current records.
public final void setLogOnlyTransitions(boolean enable):Set to log only messages that cause a state transition.
public final int getLogRecSize() :return the number of log records currently readable.
public final int getLogRecMaxSize() :return the number of log records we can store.
public final int getLogRecCount() :return the total number of records processed.
public final LogRec getLogRec(int index):return a log record, or null if index is out of range.
public final Collection<LogRec> copyLogRecs() :return a copy of LogRecs as a collection.
public void addLogRec(String string):Add the string to LogRecords.
public final Handler getHandler():return Handler, maybe null if state machine has quit.
public final Message obtainMessage():Get a message and set Message.target state machine handler.
public final Message obtainMessage(int what) :Get a message and set Message.target state machine handler, what.
public final Message obtainMessage(int what, Object obj) :Get a message and set Message.target state machine handler, what and obj.
public final Message obtainMessage(int what, int arg1) :Get a message and set Message.target state machine handler,  what, arg1 and arg2.
public final Message obtainMessage(int what, int arg1, int arg2) :Get a message and set Message.target state machine handler, what, arg1 and arg2.
public final Message obtainMessage(int what, int arg1, int arg2, Object obj) :Get a message and set Message.target state machine handler, what, arg1, arg2 and obj.
public void sendMessage(int what):Enqueue a message to this state machine.
public void sendMessage(int what, Object obj):Enqueue a message to this state machine.
public void sendMessage(int what, int arg1) :Enqueue a message to this state machine.
public void sendMessage(int what, int arg1, int arg2):Enqueue a message to this state machine.
public void sendMessage(int what, int arg1, int arg2, Object obj):Enqueue a message to this state machine.
public void sendMessage(Message msg) :Enqueue a message to this state machine.
public void sendMessageDelayed(int what, long delayMillis) :Enqueue a message to this state machine after a delay.
public void sendMessageDelayed(int what, Object obj, long delayMillis):Enqueue a message to this state machine after a delay.
public void sendMessageDelayed(int what, int arg1, long delayMillis):Enqueue a message to this state machine after a delay.
public void sendMessageDelayed(int what, int arg1, int arg2, long delayMillis) :Enqueue a message to this state machine after a delay.
public void sendMessageDelayed(int what, int arg1, int arg2, Object obj, long delayMillis) :Enqueue a message to this state machine after a delay.
public void sendMessageDelayed(Message msg, long delayMillis):Enqueue a message to this state machine after a delay.
public final void quit():Quit the state machine after all currently queued up messages are processed.
public final void quitNow() :Quit the state machine immediately all currently queued messages will be discarded.
public boolean isDbg():return if debugging is enabled.
public void setDbg(boolean dbg):Set debug enable/disabled.
public void start() :Start the state machine.
public static class LogRec {
    public void update(StateMachine sm, Message msg, String info, IState state, IState     orgState, IState dstState):Update the information in the record.
    public long getTime() :return time stamp
    public long getWhat():return msg.what
    public String getInfo() :return the command that was executing
    public IState getState() :return the state that handled this message
    public IState getDestState() :return the state destination state if a transition is occurring or null if none.
    public IState getOriginalState() :return the original state that received the message.
}

IState

Android中的IState是一个接口,用于定义状态机中的状态。它是一个抽象类,用于定义状态机中的状态。IState接口定义了状态机中的状态所需实现的方法。通过实现IState接口,可以创建自定义的状态,并在状态机中使用这些状态。

IState文件路径:

frameworks/base/core/java/com/android/internal/util/IState.java

IState定义:

public interface IState {
    void enter():Called when a state is entered.
    void exit():Called when a state is exited.
    boolean processMessage(Message msg):Called when a message is to be processed by the state machine.
    String getName();
}

State

用于在 StateMachine 中实现状态的类,State状态的基类,stateMachine中的状态都是由State派生而来,构造函数protected,不能实例化。

State文件路径:

frameworks/base/core/java/com/android/internal/util/State.java

State定义:

public class State implements IState {}

State 方法:

protected State() :构造方法
public void enter():进入状态
public void exit() :退出状态
public boolean processMessage(Message msg):消息处理
String getName():获取名字

三、Android状态机流程分析

StatMachine创建流程分析

Android13 StatMachine创建流程分析-CSDN博客

StatMachine addState流程分析

Android13 StatMachine addState流程分析-CSDN博客

StatMachine removeState流程分析

Android13 StatMachine removeState流程分析-CSDN博客

StatMachine setInitialState流程分析

Android13 StatMachine setInitialState流程分析-CSDN博客

StatMachine transitionTo流程分析

Android13 StatMachine transitionTo流程分析-CSDN博客

StatMachine obtainMessage流程分析

Android13 StatMachine obtainMessage流程分析-CSDN博客

StatMachine sendMessage流程分析

Android StatMachine sendMessage流程分析-CSDN博客

StatMachine start流程分析

Android13 StatMachine start流程分析-CSDN博客

StatMachine quit流程分析

Android13 StatMachine quit流程分析-CSDN博客

StatMachine quitNow流程分析

Android13 StatMachine quitNow流程分析-CSDN博客

  • 23
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值