Tori
Tori

Reputation: 1356

State Machine and Intents

My android app needs to run through a sequence of events as in a state machine

Event 1: play video # 1

Event 2: load an image and wait for a button press

Event 3: play video #2

etc...

One way of doing would be to generate a separate activity for each event, but with over 20 events, I thought there's an easier way of doing it.

So I coded a state machine like this:

    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;
}

Questions: After starting the intent to play the video (that activity has a listener to wait for the completion) and then finish() is called.

  1. Where will finish() come back to onCreate, onResume or another method?

  2. How do I get back to the switch statement?

  3. Any better ways of doing this?

Upvotes: 1

Views: 649

Answers (2)

xixixao
xixixao

Reputation: 563

You might consider either sublassing the Application or passing in the state value with the Intent. You should consider what should happen when user leaves the application in any of your states.

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.

Upvotes: 1

mah
mah

Reputation: 39837

The startActivity() method is non-blocking, so your loop (assuming you're considering a loop in your onCreate() method) would cycle through before the video completed. You could instead perform startActivityForResult(), which would cause a callback in your (current) activity to be called when the started activity finish()'d. You could also load your image without waiting since the new activity will cause yours to be hidden.

Upvotes: 1

Related Questions