import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "gyroscopedemo";
private SensorManager sensorManager;
private TextView tvMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
findViews();
}
private void findViews() {
tvMessage = (TextView) findViewById(R.id.tvMessage);
}
// 重點就是這個 listener , type 是 SensorEventListener()
SensorEventListener listener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
String sensorInfo = "";
sensorInfo += "sensor name: " + sensor.getName() + "\n";
sensorInfo += "sensor type: " + sensor.getType() + "\n";
sensorInfo += "used power: " + sensor.getPower() + " mA\n";
sensorInfo += "values: \n";
float[] values = event.values; // 資料都在這裡面
for (int i = 0; i < values.length; i++) {
// 把弧度改成角度....
sensorInfo += "-values[" + i + "] = " + Math.toDegrees(values[i]) + "\n";
}
tvMessage.setText(sensorInfo);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Called when the accuracy of a sensor has changed.
}
};
// 註冊一個listener... 當sensor產生變化的時候就呼叫這個listener...
@Override
protected void onResume() {
super.onResume();
boolean enable = sensorManager.registerListener(listener,
sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), // 選擇陀螺儀
SensorManager.SENSOR_DELAY_UI);
if (!enable) {
sensorManager.unregisterListener(listener); // 如果註冊不成功...就把這個listener 取消
Log.e(TAG, getString(R.string.msg_SensorNotSupported));
}
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(listener);
}
}
沒有留言:
張貼留言