如何将蓝牙设备连接通过单击列表视图的Andr​​oid的项目? [英] How to connect the Bluetooth device by click the item of listview in Android?

查看:189
本文介绍了如何将蓝牙设备连接通过单击列表视图的Andr​​oid的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个应用程序,我必须连接到蓝牙设备上的Andr​​oid 4.3。

I am developing an application where I have to connect to Bluetooth device on Android 4.3.

我可以扫描蓝牙设备,但它不能连接的蓝牙设备。

I can scan the bluetooth device, but it can not connect the bluetooth device.

我已经添加的权限在清单如下:

I have already add the permission in Manifest of the following:

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

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

My Operation is when I push SCAN Button, it will scan the Bluetooth device and show on the ListView.

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

When I click the bluetooth device on ListView,it will connect the bluetooth device of item.

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

But when I click the device item, the app will crash, and I don't know why...

这是我的Java code:

This is my java code:

     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 的连接code,它总是崩溃。

when I type the connect code of following into new_devices_list.setOnItemClickListener, it always crash.

//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();
        }

我不知道,但问题看起来像这行:

I am not sure, but the problem look like in this line:

BluetoothDevice类connect_device = mBluetoothAdapter.getRemoteDevice(地址);

地址的数据类型是字符串,而解决。

但我选择getRemoteDevice的类型为字符串的地址。

But the type of getRemoteDevice I choose is String address.

所以...我不知道,当我在new_devices_list键入连接code为什么总是应用程序崩溃,甚至??

SO...I don't know Why the app always crash when I type the connect code in new_devices_list even??

难道就不能在使用Android 4.3的??

Does it can not be use in Android 4.3 ??

有人能教教我吗?

谢谢!

推荐答案

它如果要连接蓝牙经典或低功耗设备不明确。您code是经典,标签表明低能。如果低能你可以使用

It was not clear if you are connecting Bluetooth Classic or a Low Energy device. Your code is for Classic, the tag suggests Low Energy. In case the Low Energy you would use

device.connectGatt(this, false, mGattCallback);

而不是

connect_device.createRfcommSocketToServiceRecord(my_UUID);

这篇关于如何将蓝牙设备连接通过单击列表视图的Andr​​oid的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆