动态添加发现蓝牙设备到ListPreference

时间:2014-02-28 13:06:42

标签: android bluetooth sharedpreferences listpreference

我有一个PreferenceFragment,其中包含以下首选xml资源:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/Preferences">

<PreferenceCategory
 android:title="@string/Bluetooth">

 <CheckBoxPreference
   android:key="pref_bt_enabled"
   android:title="@string/Bt_checkbox"
   android:summary="@string/Bt_checkbox_summary"
   android:defaultValue="false" />

 <ListPreference 
    android:key="pref_bt_devices"
    android:summary="@string/Bt_devices_summary"
    android:title="@string/Bt_devices"
    android:enabled="false" />

</PreferenceCategory>

</PreferenceScreen>

我要做的是: 当我启用pref_bt_enabled时,我打开蓝牙,查找配对设备,并发现其他设备并将它们全部添加到ListPreference。这是我到目前为止使用的代码:

public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {

private static final int REQUEST_ENABLE_BT = 100;

BluetoothAdapter btAdapter;
Set<BluetoothDevice> pairedDevices;
Set<BluetoothDevice> discoveredDevices;
ListPreference btDevicesList;
ArrayList<CharSequence> entries;
ArrayList<CharSequence> entryValues;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    btDevicesList = (ListPreference) findPreference("pref_bt_devices");

    btAdapter = getBtAdapter();
    if (btAdapter != null) {
        findPreference("pref_bt_enabled").setEnabled(true);
    }

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    getActivity().registerReceiver(btDiscoveryReceiver, filter);
}

@Override
public void onResume() {
    super.onResume();
    // Set up a listener whenever a key changes
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
    super.onPause();
    // Set up a listener whenever a key changes
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

@Override
public void onDestroy() {
    super.onPause();
    getActivity().unregisterReceiver(btDiscoveryReceiver);
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals("pref_bt_enabled")) {
        if (sharedPreferences.getBoolean(key, false) == true) {
            enableBluetooth();
            findPairedDevices();
            discoverDevices();
            btDevicesList.setEnabled(true);
        }
        else {
            btAdapter.disable();
            btDevicesList.setEnabled(false);
        }
    }
}

public BluetoothAdapter getBtAdapter() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        // Device does not support Bluetooth
        return null;
    }
    else {
        return mBluetoothAdapter;
    }
}

public void enableBluetooth() {
    if (!btAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}

public void findPairedDevices() {
    pairedDevices = btAdapter.getBondedDevices();
    entries = new ArrayList<CharSequence>();
    entryValues = new ArrayList<CharSequence>();
    for (BluetoothDevice d : pairedDevices) {
        entries.add("paired: " + d.getName());
        entryValues.add(d.getAddress());
    }
    btDevicesList.setEntries(listToArray(entries));
    btDevicesList.setEntryValues(listToArray(entryValues));
}

public void discoverDevices() {
    btAdapter.startDiscovery();
}

public CharSequence[] listToArray(ArrayList<CharSequence> list) {
    CharSequence[] sequence = new CharSequence[list.size()];
    for (int i = 0; i < list.size(); i++) {
        sequence[i] = list.get(i);
    }
    return sequence;
}

private final BroadcastReceiver btDiscoveryReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            discoveredDevices.add(device);

            entries.add("discovered: " + device.getName());
            btDevicesList.setEntries(listToArray(entries));

            entryValues.add(device.getAddress());
            btDevicesList.setEntryValues(listToArray(entryValues));

        }
    }
};

}

当我使用我的复选框打开蓝牙时,蓝牙会打开,但即使我有蓝牙设备,我的ListPreference仍然为空,并且可以被发现。运行此代码时没有错误。谢谢你的建议!

1 个答案:

答案 0 :(得分:0)

你的代码实际上是在btDiscoveryReceiver中抛出一个异常,从来没有初始化foundDevices。