@Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.connect:
        proceedWithConnection = true;
        if (getConnectionState() == BluetoothSerialService.STATE_NONE) {
          if (!mEnablingBT) { // If we are turning on the BT we cannot check if it's enable
            if ((mBluetoothAdapter != null) && (!mBluetoothAdapter.isEnabled())) {
              proceedWithConnection = false;
              AlertDialog.Builder builder = new AlertDialog.Builder(this);
              builder
                  .setMessage(R.string.alert_dialog_turn_on_bt)
                  .setIcon(android.R.drawable.ic_dialog_alert)
                  .setTitle(R.string.alert_dialog_warning_title)
                  .setCancelable(false)
                  .setPositiveButton(
                      R.string.alert_dialog_yes,
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                          mEnablingBT = true;
                          Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                          startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                        }
                      })
                  .setNegativeButton(
                      R.string.alert_dialog_no,
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
            }

            if (mSerialService != null) {
              // Only if the state is STATE_NONE, do we know that we haven't started already
              if (mSerialService.getState() == BluetoothSerialService.STATE_NONE) {
                // Start the Bluetooth chat services
                mSerialService.start();
              }
            }
          }
          if (proceedWithConnection) {
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
          }
        } else if (getConnectionState() == BluetoothSerialService.STATE_CONNECTED) {
          mSerialService.stop();
          mSerialService.start();
        }
        return true;
        // case R.id.preferences:
        // doPreferences();
        // return true;
        // case R.id.menu_special_keys:
        // doDocumentKeys();
        // return true;
    }
    return false;
  }
 public void onDestroy() {
   super.onDestroy();
   if (mSerialService != null) mSerialService.stop();
 }