Skip to content

Instantly share code, notes, and snippets.

@sng2c
Last active March 15, 2016 01:59
Show Gist options
  • Save sng2c/afca55a5a14aed2c26f6 to your computer and use it in GitHub Desktop.
Save sng2c/afca55a5a14aed2c26f6 to your computer and use it in GitHub Desktop.
XFSM example for Android with Android Annotations
@EBean
public class FSM extends XFSM {
private static final String TAG = "FSM";
@RootContext
Context context;
Thread consumerThread;
public RuleSet getRuleSet() {
InputStream is = context.getResources().openRawResource(R.raw.dazy);
try {
BufferedReader bs = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String buf;
while ((buf = bs.readLine()) != null) {
sb.append(buf).append("\n");
}
String uml = sb.toString();
return new PlantUmlParser().parse(uml);
} catch (IOException e) {
Log.e(TAG, "Can't read state_uml.", e);
}
return null;
}
@AfterInject
void afterInject() {
setRuleSet(getRuleSet());
}
@Override
public void init() {
super.init();
consumerThread = new Thread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "start fsm loop");
try {
loop();
} catch (InterruptedException e) {
Log.d(TAG, "loop stopped");
}
}
});
consumerThread.start();
}
public void stopLoop(){
consumerThread.interrupt();
}
}
@EService
public class FSMService extends Service implements XFSM.ActionListener {
@Bean
FSM fsm;
@AfterInject
void afterInject() {
fsm.setActionListener(this);
fsm.init();
}
@Override
public void onAction(XFSM xfsm, XFSM.When when, String action) {
Log.i(TAG, "state:" + xfsm.getCurrentState().name + ", when:" + when + ", action:" + action);
call(action);
}
public void call(String action) {
try {
Method method = this.getClass().getMethod(action);
method.invoke(this);
} catch (Exception e) {
Log.w(TAG, "Calling " + action, e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment