如何通过点击Android中的listview项来连接蓝牙设备?

时间:2013-10-02 07:44:57

标签: android listview bluetooth bluetooth-lowenergy android-bluetooth

我正在开发一个应用程序,我必须连接到Android 4.3上的蓝牙设备。

我可以扫描蓝牙设备,但无法连接蓝牙设备。

我已经在Manifest中添加了以下内容的权限:

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

我的操作是当我按下SCAN按钮时,它将扫描蓝牙设备并在ListView上显示。

当我点击ListView上的蓝牙设备时,它将连接项目的蓝牙设备。

但是当我点击设备项目时,应用程序会崩溃,我不知道为什么......

这是我的java代码:

     package com.example.preventthelost;


        import java.io.IOException;
        import java.net.Socket;
        import java.util.Set;
        import java.util.UUID;

        import android.os.Bundle;
        import android.app.Activity;
        import android.app.AlertDialog;
        import android.bluetooth.BluetoothAdapter;
        import android.bluetooth.BluetoothDevice;
        import android.bluetooth.BluetoothSocket;
        import android.widget.AdapterView;
        import android.widget.AdapterView.OnItemClickListener;
        import android.widget.ArrayAdapter;
        import android.widget.Button;
        import android.widget.ListView;
        import android.widget.TextView;
        import android.content.BroadcastReceiver;
        import android.content.Context;
        import android.content.DialogInterface;
        import android.content.Intent;
        import android.content.IntentFilter;
        import android.util.Log;
        import android.view.Menu;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Toast;

        public class DeviceList extends Activity {

            protected static final String tag = "TAG";
            private BluetoothAdapter mBluetoothAdapter;
            private static final int REQUEST_ENABLE_BT=1;
            private Button btn_cancel;
            private Button btn_scan;
            private ListView pair_devices_list;
            private ListView new_devices_list;
            private Set<BluetoothDevice> pairedDevice;
            private ArrayAdapter<String> newDevicelistArrayAdapter;
            private ArrayAdapter<String> pairDevicelistArrayAdapter;
            private final UUID my_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
            //private final UUID my_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
            private BluetoothSocket socket;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.device_list);

                btn_scan = (Button)findViewById(R.id.btn_scan);

                newDevicelistArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
                new_devices_list = (ListView)findViewById(R.id.new_devices_list);
                new_devices_list.setAdapter(newDevicelistArrayAdapter);


                 **//check device support bluetooth or not**
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if(mBluetoothAdapter == null) {
                    Toast.makeText(this, "No support bluetooth", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }else if(!mBluetoothAdapter.isEnabled()){ **//if bluetooth is close, than open it**
                    Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
                }


                **//click the scan button**
                btn_scan.setOnClickListener(new OnClickListener() {         
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        //**list the bluetooth device**
                        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                        registerReceiver(mReceiver, filter);
                        mBluetoothAdapter.startDiscovery();
                        newDevicelistArrayAdapter.clear();
                    }
                });

                //new_devices_list click
                new_devices_list.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                            long arg3) {
                        // TODO Auto-generated method stub          

                        mBluetoothAdapter.cancelDiscovery();
                        final String info = ((TextView) arg1).getText().toString();

             //get the device address when click the device item
                        String address = info.substring(info.length()-19);

                     //connect the device when item is click
              BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);

                    try {
                        socket = connect_device.createRfcommSocketToServiceRecord(my_UUID);
                        socket.connect();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    }
                });//************new_devices_list end


            }

            public final BroadcastReceiver mReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    // TODO Auto-generated method stub
                    String action = intent.getAction();
                    if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                        BluetoothDevice bdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);              
                        //short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);;
                        if(bdevice.getBondState() != BluetoothDevice.BOND_BONDED)   
                        newDevicelistArrayAdapter.add("\n" + bdevice.getName() + "\n" + bdevice.getAddress());
                        newDevicelistArrayAdapter.notifyDataSetChanged();

                    }
                }
            };


            protected void onDestroy() {

                super.onDestroy();
                if(mBluetoothAdapter != null)
                    mBluetoothAdapter.cancelDiscovery();
                unregisterReceiver(mReceiver);
            }

            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.device_list, menu);
                return true;
            }
        }

当我将下面的连接代码输入new_devices_list.setOnItemClickListener时,它总会崩溃。

//get the device address when click the device item
String address = info.substring(info.length()-19);

//connect the device when item is click
BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);

        try {
            socket = connect_device.createRfcommSocketToServiceRecord(my_UUID);
            socket.connect();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

我不确定,但问题看起来像这一行:

BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);

address的数据类型是String而不是地址。

但我选择的getRemoteDevice的类型是String address。

所以...我不知道为什么当我在new_devices_list中键入连接代码时应用程序总是崩溃?

它是否无法在Android 4.3中使用?

有人可以教我吗?

谢谢!

3 个答案:

答案 0 :(得分:3)

目前尚不清楚您是否正在连接Bluetooth Classic或Low Energy设备。您的代码适用于Classic,标签显示Low Energy。如果您将使用低能量

device.connectGatt(this, false, mGattCallback);

而不是

connect_device.createRfcommSocketToServiceRecord(my_UUID);

答案 1 :(得分:1)

您选择标记BluetoothLowEnergy。您的问题是关于BLE还是标准蓝牙?对于BLE,还有另一种连接方法。您可以阅读here

答案 2 :(得分:1)

我遇到了类似的问题,但刚刚找到了解决方案。

而不是从<{p>中的info.length()中减去19

String address = info.substring(info.length()-19);

减去17。原帖几乎在一年前发布,但希望它仍然对那些有同样问题的人有帮助。