1

我的 android 应用程序需要像在状态机中一样运行一系列事件

事件一:播放视频#1

事件 2:加载图像并等待按钮按下

活动 3:播放视频 #2

ETC...

一种方法是为每个事件生成一个单独的活动,但是有超过 20 个事件,我认为有一种更简单的方法。

所以我编写了这样的状态机:

    int mState = 0;     
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //
    switch(mState) {
    case 0:
        Boolean flag = videoIntent(url0); 
        break;
    case 1:
        flag = loadImage(img1);
    }
    }


public Boolean videoIntent(String video) {
     mBundle.putString("url",video ); 
     Intent myIntent = new Intent();
     myIntent.putExtras(mBundle);
         myIntent.setClass(mySM.this, SM_vPlayer.class);
         startActivity(myIntent);
             mState ++;
    return true;     
 }

public Boolean loadImage(String image) {
    //load image
            mState ++;
    return true;
}

问题:在开始播放视频的意图后(该活动有一个监听器等待完成),然后调用完成()。

  1. finish() 将在哪里返回 onCreate、onResume 或其他方法?

  2. 如何回到 switch 语句?

  3. 有更好的方法吗?

4

2 回答 2

1

startActivity()方法是非阻塞的,因此您的循环(假设您正在考虑 onCreate() 方法中的循环)将在视频完成之前循环播放。您可以改为 perform startActivityForResult(),这将导致您的(当前)活动中的回调在启动的活动完成()时被调用。您也可以在不等待的情况下加载您的图像,因为新活动将导致您的图像被隐藏。

于 2012-07-15T21:24:28.827 回答
1

您可能会考虑将应用程序子类化或使用 Intent 传递状态值。您应该考虑当用户在您的任何状态下离开应用程序时会发生什么。

For example, you could always pass in the state value, increase it when the action inside the event is finished and call an Application/static method, which returns the intent that should triggered next. This way, you preserve the back trace and keep your state logic in one place.

于 2012-07-15T21:51:06.037 回答