public void toggleDriveMode(View view) { if (!gyroMode) { forwardButton.setVisibility(View.INVISIBLE); backwardButton.setVisibility(View.INVISIBLE); gyroMode = true; toggleButton.setText("Switch to Buttons"); } else { forwardButton.setVisibility(View.VISIBLE); backwardButton.setVisibility(View.VISIBLE); gyroMode = false; toggleButton.setText("Switch to Gyro Mode"); } spacialSensorListener.setGyroMode(gyroMode); forwardMotionExecutor.setMotion(ForwardMotionExecutor.MOTION_DECELERATE); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); forwardButton = (Button) findViewById(R.id.forward); backwardButton = (Button) findViewById(R.id.backward); toggleButton = (Button) findViewById(R.id.toggleMode); stepButton = (Button) findViewById(R.id.stepMode); speedometer = (TextView) findViewById(R.id.speedometer); forwardMotionExecutor = new ForwardMotionExecutor(new Handler(), this); spacialSensorListener = new SpacialSensorListener(forwardMotionExecutor, this); // Default to begin in "Drive" mode. gyroMode = false; spacialSensorListener.setGyroMode(gyroMode); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth. } if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } mArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); magneticField = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); gravField = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR); sensorManager.registerListener( spacialSensorListener, magneticField, SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener( spacialSensorListener, gravField, SensorManager.SENSOR_DELAY_GAME); forwardButton.setOnTouchListener( new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: forwardMotionExecutor.setMotion(ForwardMotionExecutor.MOTION_FORWARD); return true; case MotionEvent.ACTION_UP: forwardMotionExecutor.setMotion(ForwardMotionExecutor.MOTION_DECELERATE); return true; } return false; } }); backwardButton.setOnTouchListener( new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: forwardMotionExecutor.setMotion(ForwardMotionExecutor.MOTION_REVERSE); return true; case MotionEvent.ACTION_UP: forwardMotionExecutor.setMotion(ForwardMotionExecutor.MOTION_DECELERATE); return true; } return false; } }); }