public void onClick(DialogInterface dialog, int which) {
          if (which == DialogInterface.BUTTON_POSITIVE) {
            if (mDevice != null) {
              if (!LocalBluetoothPreferences.hasDockAutoConnectSetting(
                  DockService.this, mDevice.getAddress())) {
                LocalBluetoothPreferences.saveDockAutoConnectSetting(
                    DockService.this, mDevice.getAddress(), true);
              }

              applyBtSettings(mDevice, mStartIdAssociatedWithDialog);
            } else if (mAudioMediaCheckbox != null) {
              Settings.Global.putInt(
                  getContentResolver(),
                  Settings.Global.DOCK_AUDIO_MEDIA_ENABLED,
                  mAudioMediaCheckbox.isChecked() ? 1 : 0);
            }
          }
        }
 private synchronized void handleDocked(BluetoothDevice device, int state, int startId) {
   if (device != null
       && LocalBluetoothPreferences.getDockAutoConnectSetting(this, device.getAddress())) {
     // Setting == auto connect
     initBtSettings(device, state, false);
     applyBtSettings(mDevice, startId);
   } else {
     createDialog(device, state, startId);
   }
 }
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
   if (DEBUG) {
     Log.d(TAG, "onCheckedChanged: Remember Settings = " + isChecked);
   }
   if (mDevice != null) {
     LocalBluetoothPreferences.saveDockAutoConnectSetting(
         DockService.this, mDevice.getAddress(), isChecked);
   } else {
     Settings.Global.putInt(
         getContentResolver(), Settings.Global.DOCK_AUDIO_MEDIA_ENABLED, isChecked ? 1 : 0);
   }
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
      // convert broadcast intent into activity intent (same action string)
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);
      Intent pairingIntent = new Intent();
      pairingIntent.setClass(context, BluetoothPairingDialog.class);
      pairingIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
      pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, type);
      if (type == BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION
          || type == BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY
          || type == BluetoothDevice.PAIRING_VARIANT_DISPLAY_PIN) {
        int pairingKey =
            intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, BluetoothDevice.ERROR);
        pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, pairingKey);
      }
      pairingIntent.setAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
      pairingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

      PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
      String deviceAddress = device != null ? device.getAddress() : null;
      if (powerManager.isScreenOn()
          && LocalBluetoothPreferences.shouldShowDialogInForeground(context, deviceAddress)) {
        // Since the screen is on and the BT-related activity is in the foreground,
        // just open the dialog
        context.startActivity(pairingIntent);
      } else {
        // Put up a notification that leads to the dialog
        Resources res = context.getResources();
        Notification.Builder builder =
            new Notification.Builder(context)
                .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
                .setTicker(res.getString(R.string.bluetooth_notif_ticker));

        PendingIntent pending =
            PendingIntent.getActivity(context, 0, pairingIntent, PendingIntent.FLAG_ONE_SHOT);

        String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
        if (TextUtils.isEmpty(name)) {
          name =
              device != null
                  ? device.getAliasName()
                  : context.getString(android.R.string.unknownName);
        }

        builder
            .setContentTitle(res.getString(R.string.bluetooth_notif_title))
            .setContentText(res.getString(R.string.bluetooth_notif_message, name))
            .setContentIntent(pending)
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setColor(res.getColor(com.android.internal.R.color.system_notification_accent_color));

        NotificationManager manager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.getNotification());
      }

    } else if (action.equals(BluetoothDevice.ACTION_PAIRING_CANCEL)) {

      // Remove the notification
      NotificationManager manager =
          (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      manager.cancel(NOTIFICATION_ID);

    } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
      int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
      int oldState =
          intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
      if ((oldState == BluetoothDevice.BOND_BONDING) && (bondState == BluetoothDevice.BOND_NONE)) {
        // Remove the notification
        NotificationManager manager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(NOTIFICATION_ID);
      }
    }
  }
  private void createDialog(BluetoothDevice device, int state, int startId) {
    if (mDialog != null) {
      // Shouldn't normally happen
      mDialog.dismiss();
      mDialog = null;
    }
    mDevice = device;
    switch (state) {
      case Intent.EXTRA_DOCK_STATE_CAR:
      case Intent.EXTRA_DOCK_STATE_DESK:
      case Intent.EXTRA_DOCK_STATE_LE_DESK:
      case Intent.EXTRA_DOCK_STATE_HE_DESK:
        break;
      default:
        return;
    }

    startForeground(0, new Notification());

    final AlertDialog.Builder ab = new AlertDialog.Builder(this);
    View view;
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

    mAudioMediaCheckbox = null;

    if (device != null) {
      // Device in a new dock.
      boolean firstTime =
          !LocalBluetoothPreferences.hasDockAutoConnectSetting(this, device.getAddress());

      CharSequence[] items = initBtSettings(device, state, firstTime);

      ab.setTitle(getString(R.string.bluetooth_dock_settings_title));

      // Profiles
      ab.setMultiChoiceItems(items, mCheckedItems, mMultiClickListener);

      // Remember this settings
      view = inflater.inflate(R.layout.remember_dock_setting, null);
      CheckBox rememberCheckbox = (CheckBox) view.findViewById(R.id.remember);

      // check "Remember setting" by default if no value was saved
      boolean checked =
          firstTime
              || LocalBluetoothPreferences.getDockAutoConnectSetting(this, device.getAddress());
      rememberCheckbox.setChecked(checked);
      rememberCheckbox.setOnCheckedChangeListener(mCheckedChangeListener);
      if (DEBUG) {
        Log.d(
            TAG,
            "Auto connect = "
                + LocalBluetoothPreferences.getDockAutoConnectSetting(this, device.getAddress()));
      }
    } else {
      ab.setTitle(getString(R.string.bluetooth_dock_settings_title));

      view = inflater.inflate(R.layout.dock_audio_media_enable_dialog, null);
      mAudioMediaCheckbox = (CheckBox) view.findViewById(R.id.dock_audio_media_enable_cb);

      boolean checked =
          Settings.Global.getInt(getContentResolver(), Settings.Global.DOCK_AUDIO_MEDIA_ENABLED, 0)
              == 1;

      mAudioMediaCheckbox.setChecked(checked);
      mAudioMediaCheckbox.setOnCheckedChangeListener(mCheckedChangeListener);
    }

    float pixelScaleFactor = getResources().getDisplayMetrics().density;
    int viewSpacingLeft = (int) (14 * pixelScaleFactor);
    int viewSpacingRight = (int) (14 * pixelScaleFactor);
    ab.setView(view, viewSpacingLeft, 0 /* top */, viewSpacingRight, 0 /* bottom */);

    // Ok Button
    ab.setPositiveButton(getString(android.R.string.ok), mClickListener);

    mStartIdAssociatedWithDialog = startId;
    mDialog = ab.create();
    mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
    mDialog.setOnDismissListener(mDismissListener);
    mDialog.show();
  }
  @Override
  public void onReceive(Context context, Intent intent) {
    mContext = context;
    String action = intent.getAction();

    if (DEBUG) Log.d(TAG, "onReceive");

    if (action.equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_REQUEST)) {
      // convert broadcast intent into activity intent (same action string)
      mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      mRequestType =
          intent.getIntExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE, BluetoothDevice.ERROR);
      mReturnPackage = intent.getStringExtra(BluetoothDevice.EXTRA_PACKAGE_NAME);
      mReturnClass = intent.getStringExtra(BluetoothDevice.EXTRA_CLASS_NAME);

      Intent connectionAccessIntent = new Intent(action);
      connectionAccessIntent.setClass(context, BluetoothPermissionActivity.class);
      connectionAccessIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      connectionAccessIntent.putExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE, mRequestType);
      connectionAccessIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, mDevice);
      connectionAccessIntent.putExtra(BluetoothDevice.EXTRA_PACKAGE_NAME, mReturnPackage);
      connectionAccessIntent.putExtra(BluetoothDevice.EXTRA_CLASS_NAME, mReturnClass);

      // Check if user had made decisions on accepting or rejecting the phonebook access
      // request. If there is, reply the request and return, no need to start permission
      // activity dialog or notification.
      if (checkUserChoice()) {
        return;
      }

      String deviceAddress = mDevice != null ? mDevice.getAddress() : null;
      PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

      if (powerManager.isScreenOn()
          && LocalBluetoothPreferences.shouldShowDialogInForeground(context, deviceAddress)) {
        context.startActivity(connectionAccessIntent);
      } else {
        // Put up a notification that leads to the dialog

        // Create an intent triggered by clicking on the
        // "Clear All Notifications" button
        Intent deleteIntent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY);
        deleteIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, mDevice);
        deleteIntent.putExtra(
            BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT, BluetoothDevice.CONNECTION_ACCESS_NO);

        int notificationId = 0;
        int stringId = 0;
        if (mRequestType == BluetoothDevice.REQUEST_TYPE_PROFILE_CONNECTION) {
          /*It looks that the extra type REQUEST_TYPE_PROFILE_CONNECTION is defined
           *to create pop up for remote initiated A2DP, HF and HID but not used for now
           */
          notificationId = NOTIFICATION_ID;
          stringId = R.string.bluetooth_connection_permission_request;
        } else if (mRequestType == BluetoothDevice.REQUEST_TYPE_PHONEBOOK_ACCESS) {
          notificationId = NOTIFICATION_ID_ACCESS_PBAP;
          stringId = R.string.bluetooth_pbap_connection_permission_request;
        } else if (mRequestType == BluetoothDevice.REQUEST_TYPE_FILE_ACCESS) {
          notificationId = NOTIFICATION_ID_ACCESS_FTP;
          stringId = R.string.bluetooth_ftp_connection_permission_request;
        } else if (mRequestType == BluetoothDevice.REQUEST_TYPE_MESSAGE_ACCESS) {
          notificationId = NOTIFICATION_ID_ACCESS_MAP;
          stringId = R.string.bluetooth_map_connection_permission_request;
        } else if (mRequestType == BluetoothDevice.REQUEST_TYPE_SIM_ACCESS) {
          notificationId = NOTIFICATION_ID_ACCESS_SAP;
          stringId = R.string.bluetooth_sap_connection_permission_request;
        } else {
          /* Unhandled request */
          return;
        }

        Notification notification =
            new Notification(
                android.R.drawable.stat_sys_data_bluetooth,
                context.getString(stringId),
                System.currentTimeMillis());
        String deviceName = mDevice != null ? mDevice.getAliasName() : null;
        notification.setLatestEventInfo(
            context,
            context.getString(stringId),
            context.getString(R.string.bluetooth_connection_notif_message, deviceName),
            PendingIntent.getActivity(
                context, notificationId, connectionAccessIntent, PendingIntent.FLAG_ONE_SHOT));
        notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.deleteIntent =
            PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_ONE_SHOT);

        NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(notificationId, notification);
      }
    } else if (action.equals(BluetoothDevice.ACTION_CONNECTION_ACCESS_CANCEL)) {
      // Remove the notification
      int notificationId = 0;
      int clearNotification =
          intent.getIntExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE, BluetoothDevice.ERROR);
      if (clearNotification == BluetoothDevice.REQUEST_TYPE_PROFILE_CONNECTION) {
        /* Not used for now */
        notificationId = NOTIFICATION_ID;
      } else if (clearNotification == BluetoothDevice.REQUEST_TYPE_PHONEBOOK_ACCESS) {
        notificationId = NOTIFICATION_ID_ACCESS_PBAP;
      } else if (clearNotification == BluetoothDevice.REQUEST_TYPE_FILE_ACCESS) {
        notificationId = NOTIFICATION_ID_ACCESS_FTP;
      } else if (clearNotification == BluetoothDevice.REQUEST_TYPE_MESSAGE_ACCESS) {
        notificationId = NOTIFICATION_ID_ACCESS_MAP;
      } else if (clearNotification == BluetoothDevice.REQUEST_TYPE_SIM_ACCESS) {
        notificationId = NOTIFICATION_ID_ACCESS_SAP;
      } else {
        /* Do not clear */
        return;
      }

      NotificationManager manager =
          (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      manager.cancel(notificationId);
    }
  }