Android Helper Classes

The minimal example above leaves a lot of inner plumbing to the implementer, for example, life-cycle management, communication failures, and key de-bouncing. Several help classes are provided to make game development simpler.

An Android activity has a complicated life full of starts and stops. To help managing the life-cycle, the class SgWatcher is provided. It watches the state of SymGym controller and calls a custom event dispatcher when needed. The event dispatcher has to implement a simple interface:

public interface SgDispatcher {
  public boolean dispatch(SgState sgState);
}    

The onCreate() method then becomes

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  new SgWatcher(new SgStub(this, "api_key_string_here"),
  new SgDispatcher(){
    @Override public boolean dispatch(SgState sgState) {
      if (sgState.isLeftTrigger()) {
        // do something about left trigger
      }
      // ... and so on.
    }
  }).start();
}    

When porting existing games, it’s beneficial to have a simple key mapping between SymGym buttons and key strokes. The SgKeyMapper class does just that. The following example shows its use:

package fit.symgym.android.examples;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;

import fit.symgym.android.api.SgStub;
import fit.symgym.android.api.SgState;
import fit.symgym.android.api.SgKeyMapper;
import fit.symgym.android.api.SgWatcher;
import fit.symgym.android.api.SgDispatcher;

public class ExampleWithKeyMapper extends Activity {
  private SgStub sgStub = null;

  class SimpleDispatcher implements SgDispatcher {
    SgKeyMapper mapper = new SgKeyMapper(ExampleWithKeyMapper.this);
    SimpleDispatcher() {
        mapper.mapLeftTrigger(KeyEvent.KEYCODE_ENTER);
        mapper.mapLeftSubTrigger(KeyEvent.KEYCODE_UNKNOWN); // no keypress
        mapper.mapLeftLeft(KeyEvent.KEYCODE_DPAD_LEFT);
        mapper.mapLeftRight(KeyEvent.KEYCODE_DPAD_DOWN);
    }

    @Override public boolean dispatch(SgState sgState) {
        return mapper.dispatchButtonPush(sgState);
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new SgWatcher(new SgStub(this, "api_key_string_here"),
                  new SimpleDispatcher()).start();
  }    
} 

In this case, when user presses the left trigger button, the activity receives ‘Enter’ key from the keyboard.