[英]Android Discover Bluetooth Devices in Fragment
So I have a fragment that is suppose to, among other things, discover Bluetooth devices and populate a ListView
. 因此,我有一个片段,除其他事项外,该片段旨在发现蓝牙设备并填充
ListView
。
Here's my code: 这是我的代码:
public class BluetoothFragment extends Fragment {
private static final String TAG = "BluetoothFragment";
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private Switch m_btSwitch;
private ListView m_btDiscoveredPeerListview;
private ArrayList<String> m_DiscoveredPeers = new ArrayList<>();
private ArrayAdapter m_DiscoveredPeersAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_bluetooth, container, false);
// Init UI elements
m_btSwitch = (Switch) view.findViewById(R.id.bt_switch);
m_btDiscoveredPeerListview = (ListView) view.findViewById(R.id.bt_discovered_peers_listview);
m_DiscoveredPeersAdapter = new ArrayAdapter(getActivity(), R.layout.row_devices, m_DiscoveredPeers);
m_btDiscoveredPeerListview.setAdapter(m_DiscoveredPeersAdapter);
m_btSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startBluetooth();
} else {
stopBluetooth();
}
...
return view;
}
private void startBluetooth() {
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 0);
}
Toast.makeText(getActivity(), "Bluetooth turned on",Toast.LENGTH_LONG).show();
// Check is Discover is already running
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mReceiver, filter);
}
private void stopBluetooth() {
Toast.makeText(getActivity(), "Bluetooth turned off",Toast.LENGTH_LONG).show();
// Turn off BT
mBluetoothAdapter.disable();
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the device info to the listview
m_DiscoveredPeers.add(device.getName() + "\n" + device.getAddress());
m_btDiscoveredPeerListview.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, m_DiscoveredPeers));
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Respond to the turn-on-Bluetooth activity; if Bluetooth is
// enabled now, start discovery
if (requestCode == 0) {
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.startDiscovery();
}
}
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mReceiver, filter);
}
};
I would like to add the discovered devices to the m_btDiscoveredPeerListview
list view and display, but right now the APP just turn on BT. 我想将发现的设备添加到
m_btDiscoveredPeerListview
列表视图并显示,但是现在APP只是打开了BT。
Thanks in advance! 提前致谢!
** UPDATE ** **更新**
I updated the code with Scott's comments, but it still doesn't fill the ListView. 我用Scott的注释更新了代码,但仍然无法填充ListView。 I'm adding the logcat to see if it helps.
我正在添加logcat以查看是否有帮助。
D/BluetoothFragment: Button is checked
D/BluetoothFragment: On BT Start
D/BluetoothAdapter: 1095832816: getState() : mService = null. Returning STATE_OFF
D/BluetoothAdapter: 1095832816: getState() : mService = null. Returning STATE_OFF
D/BluetoothFragment: End of BT Start
D/AbsListView: unregisterIRListener() is called
D/AbsListView: unregisterIRListener() is called
D/AbsListView: unregisterIRListener() is called
D/BluetoothAdapter: onBluetoothServiceUp: android.bluetooth.IBluetooth$Stub$Proxy@414040b0
D/AbsListView: unregisterIRListener() is called
you should add some permission just like this and check it when you discover devices: 您应该像这样添加一些权限,并在发现设备时进行检查:
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck =getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
Declare the ArrayList of device information and the ArrayAdapter as module variables. 声明设备信息的ArrayList和ArrayAdapter作为模块变量。 After you declare m_btSwitch, add this code:
声明m_btSwitch之后,添加以下代码:
ArrayList<String> m_deviceList;
ArrayAdapter m_deviceListAdapter;
Initialize those two module variables and attach the adapter to the listview inside onCreateView(), right after your findViewById calls: 在您的findViewById调用之后,初始化这两个模块变量并将适配器附加到onCreateView()中的列表视图:
m_deviceList = new ArrayList<>();
m_deviceListAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, list);
m_btDiscoveredPeerListview.setAdapter(adapter);
Update part of your onCheckedChanged() method a bit to start discovery if Bluetooth is enabled: 如果启用了蓝牙,请稍微更新onCheckedChanged()方法的一部分以开始发现:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
}
Toast.makeText(getActivity(), "Bluetooth turned on",Toast.LENGTH_LONG).show();
mBluetoothAdapter.startDiscovery();
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mReceiver, filter);
}
}
Then update your BroadcastReceiver code to look like this: 然后更新您的BroadcastReceiver代码,如下所示:
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the device info to the listview
m_deviceList.add(device.getName() + device.getAddress());
m_deviceListAdapter.notifyDataSetChanged();
}
}
};
Finally, you'll need to add some code to your fragment's onActivityResult method: 最后,您需要向片段的onActivityResult方法中添加一些代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Respond to the turn-on-Bluetooth activity; if Bluetooth is
// enabled now, start discovery
if (requestCode == 0) {
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.startDiscovery();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.