1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.android.car.obd2app; 18 19 import android.bluetooth.BluetoothAdapter; 20 import android.bluetooth.BluetoothDevice; 21 import android.content.Context; 22 import android.preference.ListPreference; 23 import android.util.AttributeSet; 24 25 import java.util.ArrayList; 26 import java.util.List; 27 28 public class BluetoothPreference extends ListPreference { 29 private static final class DeviceEntry { 30 private final String mName; 31 private final String mAddress; 32 DeviceEntry(BluetoothDevice device)33 DeviceEntry(BluetoothDevice device) { 34 mAddress = device.getAddress(); 35 if (device.getName() == null) { 36 mName = mAddress; 37 } else { 38 mName = device.getName(); 39 } 40 } 41 getName()42 String getName() { 43 return mName; 44 } 45 getAddress()46 String getAddress() { 47 return mAddress; 48 } 49 } 50 BluetoothPreference(Context context, AttributeSet attrs)51 public BluetoothPreference(Context context, AttributeSet attrs) { 52 super(context, attrs); 53 54 BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter(); 55 List<DeviceEntry> pairedDevices = new ArrayList<>(); 56 defaultAdapter 57 .getBondedDevices() 58 .forEach((BluetoothDevice device) -> pairedDevices.add(new DeviceEntry(device))); 59 setEntries(pairedDevices.stream().map(DeviceEntry::getName).toArray(String[]::new)); 60 setEntryValues(pairedDevices.stream().map(DeviceEntry::getAddress).toArray(String[]::new)); 61 } 62 BluetoothPreference(Context context)63 public BluetoothPreference(Context context) { 64 this(context, null); 65 } 66 } 67