我有以下代码:
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();
}
}
代码正在工作,但我的问题是:当我以这种方式从主要活动中调用它时:
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
}
然后我可以看到 10 次“做其他事情!!!”的结果 当循环结束时,我可以看到活动的结果。所以传感器活动出于某种原因等待,然后当主要活动无事可做时,传感器正在做他们的工作。
当然我已经很好地实现了:onActivityResult(int requestCode, int resultCode, Intent intent)
我想直接读取传感器数据,而不是使用侦听器,可以吗?