I have following code:
public class readSensorsData extends Activity implements SensorListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
public void onSensorChanged(int sensor, float[] values) {
synchronized (this) {
if (sensor == SensorManager.SENSOR_ORIENTATION) {
//get orientation
}
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
//get acceleration
}
}
if (sensor == SensorManager.SENSOR_MAGNETIC_FIELD) {
//get magnetic fiels
}
Bundle bundle = new Bundle(); //results from activity
bundle.putFloatArray("acceleration", array);
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}
public void onAccuracyChanged(int sensor, int accuracy) {
}
@Override
protected void onResume() {
super.onResume();
sm.registerListener(this,
SensorManager.SENSOR_ORIENTATION |
SensorManager.SENSOR_ACCELEROMETER |
SensorManager.SENSOR_MAGNETIC_FIELD,
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
sm.unregisterListener(this);
super.onStop();
}
}
code is working but here goes my problem: when I call it from main activity in this way:
Intent i = new Intent(this, readSensorsData.class);
startActivityForResult(i, 1); //1 is for sensors
for(int j=0;j<10;j++)
{
//do sth else here!!!!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {e.printStackTrace();}
//here code for showing result from sensor activity
}
then i can see 10 times result of ‘doing sth else!!!’ and when loop is over i can see then result from activity. So sensor activity waits for some reason and then when main activity has nothing to do, sensors are doing their job.
of course I have well implemented: onActivityResult(int requestCode, int resultCode, Intent intent)
I want to read sensord data directly, not using listeners, is it possible?
First, never call
Thread.sleep()in the main application thread.Second,
startActivityForResult()is asynchronous. The other activity will not have started whenstartActivityForResult()returns.Third, sensor events are asynchronous.
It cannot start until you get out of the main application thread, which is being tied up by your
Thread.sleep()calls.Precisely.
No. Just use the listeners properly. Here are three sample projects showing the use of sensor listeners.