2016年7月20日 星期三

加速計on android


用的方法和陀螺儀差不多...只差在

 sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)

這個選項...



public class MainActivity extends Activity {

private static final String TAG = "MainActivity";
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);
    }
   
    SensorEventListener listener = new SensorEventListener() {
        @Override
        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 + "] = " + values[i] + "\n";
            }
            tvMessage.setText(sensorInfo);
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // Called when the accuracy of a sensor has changed.
        }
    };
   
    @Override
    protected void onResume() {
        super.onResume();
        boolean enable = sensorManager.registerListener(listener,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_UI);
        if (!enable) {
            sensorManager.unregisterListener(listener);
            Log.e(TAG, getString(R.string.msg_SensorNotSupported));
        }
    }

   
}

沒有留言:

張貼留言