Android发现片段中的蓝牙设备

时间:2017-10-19 22:31:52

标签: android android-studio android-fragments android-bluetooth

所以我有一个片段,其中包括发现蓝牙设备并填充ListView

这是我的代码:

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);

  }

};

我想将已发现的设备添加到m_btDiscoveredPeerListview列表视图并显示,但现在APP只需打开BT。

提前致谢!

**更新**

我使用Scott的评论更新了代码,但它仍然没有填充ListView。我正在添加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 

2 个答案:

答案 0 :(得分:1)

您应该像这样添加一些权限,并在发现设备时进行检查:

 @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.");
    }
}

答案 1 :(得分:0)

将设备信息的ArrayList和ArrayAdapter声明为模块变量。声明m_btSwitch后,添加以下代码:

ArrayList<String> m_deviceList;
ArrayAdapter m_deviceListAdapter;

初始化这两个模块变量并在findViewById调用之后立即将适配器附加到onCreateView()内的listview:

m_deviceList = new ArrayList<>();
m_deviceListAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, list);
m_btDiscoveredPeerListview.setAdapter(adapter);

如果启用了蓝牙,请稍微更新部分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);
    }
}

然后将您的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();
        }
    }
};

最后,您需要在片段的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();
        }
    }

}