I am working on a game that involves using the accelerometer to control the character. My problem is this: I need to use the values recieved by the sensor in classes and methods that are not accessible inside OnSensorChanged(). I believe I need to implement a Callback from inside the OnSensorChanged, but I don't know how to do that. Can anyone help me out?
I believe the answer in this post (How to Define Callbacks in Android?) will help you out.
To summarize, create the callback interface:
// The callback interface
interface MyCallback {
void callbackCall(SensorEvent event);
}
Implement the call back interface in the class that is supposed to do calculations:
class Callback implements MyCallback {
void callbackCall(SensorEvent event) {
// callback code goes here
}
}
Make the call from your Activity where you have the onSensoreChanged():
// The class that takes the callback
class Worker extends Activity implements SensorEventListener {
MyCallback callback;
public void onSensorChanged(SensorEvent event) {
callback.callbackCall(event);
}
}
I hope this helps.
UPDATE:
I assume you already know about processes and threads (if not, please have a look at the Android doc about Processes and Threads).
The onSensorChanged method is an I/O and it is a good practice to do I/O operations in a separate thread (instead of the main UI thread).
Once the callback method is called, you can store the event in another variable and use those local variables in that class.
Since you are writing a game, it is unlikely for your app to require every single event. Therefore, while the app is busy calculating data for your game, the other events can be dropped. You can do this by setting a "busy" flag (boolean) and include the code for calculation within this if block.
void callbackCall(SensorEvent event) {
if (!busy) {
// Set the busy flag to block other event changes
busy = true;
// callback code goes here
// Once finished, reset the busy flag to allow other events to come in
busy = false;
}
}