Since I recently added sensor callback support to Android Hecl, I thought I’d write about the process of doing so. It’s really pretty easy.
Ideally, it would not be necessary to write and compile any Java code to create callbacks in Hecl – you could do it all inline. However, I don’t think this is possible at the current time with Android’s bytecode engine, although I could be mistaken. It would be necessary to generate a class, or hang some new methods on an existing class. So, for the time being, we do it the old fashioned way whenever anyone wants a new callback to utilize:
The heart of the matter is this class:
public class HeclCallback implements
android.app.DatePickerDialog.OnDateSetListener,
android.app.TimePickerDialog.OnTimeSetListener,
android.hardware.SensorListener,
android.widget.AdapterView.OnItemClickListener,
android.widget.AdapterView.OnItemSelectedListener,
android.widget.CompoundButton.OnCheckedChangeListener,
android.widget.DatePicker.OnDateChangedListener,
android.widget.TimePicker.OnTimeChangedListener,
android.view.View.OnClickListener {
Which as you can see, implements the various Java listener classes. Each of these requires one or more methods to be implemented in order to receive the actual callbacks. Generally, they are done like so:
public void onItemSelected(AdapterView parent, View v, int position, long id) {
try {
Vector vec = ListThing.get(script.deepcopy());
vec.add(ObjectThing.create(parent));
vec.add(ObjectThing.create(v));
vec.add(IntThing.create(position));
vec.add(LongThing.create(id));
interp.eval(ListThing.create(vec));
} catch (HeclException he) {
Hecl.logStacktrace(he);
Log.v("hecl onitemselected callback", he.toString());
}
}
Which is pretty simple as well: the objects that are passed in are wrapped up as Hecl Things, and then the command is run.
The command to use is set from Hecl like so, when we create a new instance of the HeclCallback class:
set callback [callback -new [list [list SelectDemo]]]
$lview setonitemclicklistener $callback
So, the steps are:
- Add an “implements” to HeclCallback.
- Define the methods that need defining, copying one of the existing methods.
- Recompile
- Use the ‘callback’ command to instantiate a new HeclCallback class with the command of your choice as the handler for callbacks.