android蓝牙入门-保证看懂学会

来源:互联网 发布:上虞干部教育培训网络 编辑:程序博客网 时间:2024/04/28 17:07

我是先学习一个蓝牙聊天程序后自己打的上面代码。下面分析两个下载链接:第一个是本次实例的代码,第二个是那个蓝牙聊天项目的视频教程和对应源代码(建议先看视频,视频很详细的介绍了蓝牙的使用代码,保证看完后,对蓝牙的使用就too easy)


一.所有关于 Bluetooth的API都在android.bluetooth包下:


BluetoothAdapter(可理解为本地蓝牙设备)
这个类代表蓝牙适配器,并且是所有蓝牙交互的入口点,通过这个类,我们可以发现其他的蓝牙设备,查询已经配对的设备;
实例化一个BluetoothDevice,BluetoothDevice使用一个已知的MAC地址,并创建一个BluetoothServerSocket监听来自其他设备的通讯。

BluetoothDevice(可理解为远程蓝牙设备)
代表一个蓝牙设备,通它可以通过BluetoothSocket向其他的蓝牙设备发出连接请求;
通过它还可以设备的信息包括:设备名称、设备地址、类型、配对状态。

BluetoothSocket(连接远程设备时用到)
代表一个蓝牙套接字接口(类似于一个TCP套接字);
它是一个连接点,允许应用程序与另一个蓝牙设备交换数据通过InputStream OutputStream。

BluetoothServerSocket(远程设备请求连接时用到)
是一个开放的服务器套接字,侦听传入请求(类似于一个TCP ServerSocket);
为了连接两个Android设备,设备必须用这个类打开一个服务器套接字;
当一个远程蓝牙设备请求连接到这个设备,如果请求的连接被接受,那么BluetoothServerSocket将返回一个已经连接的BluetoothSocket对象。

广播

BluetoothDevice.ACTION_FOUND                      //查找设备BluetoothAdapter.ACTION_DISCOVERY_FINISHED      //查找完成BluetoothDevice.ACTION_ACL_CONNECTED             //连接设备BluetoothDevice.ACTION_ACL_DISCONNECTED         //断开连接
二.代码

本次代码只到连接到蓝牙设备,关于IO通信的还待扩展。这里只讲大概流程,具体细节代码在下面会分享一个链接。

第一步:打开蓝牙设备,并先存入设备和显示已配对设备名称    private void openAndFindBTDevice() {        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();        if (mBluetoothAdapter == null) {            Log.e(TAG, "Your device is not support Bluetooth!");            return;        }        if (!mBluetoothAdapter.isEnabled()) {            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);            startActivityForResult(enableBtIntent, REQUEST_ENABLE_CODE);        } else {            findBTDevice();        }    }    private void findBTDevice() {        // 用来保存已经配对的蓝牙设备对象        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();        if (pairedDevices.size() > 0) {            for (BluetoothDevice device : pairedDevices) {                // 将已经配对设备信息添加到ListView中                mArrayAdapter.add(device.getName());                mDeviceList.add(device);            }        }        adapter.notifyDataSetChanged();    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        if (requestCode == REQUEST_ENABLE_CODE) {            if (resultCode == RESULT_OK) {                System.out.println("设备打开成功");                findBTDevice();            } else {                System.out.println("设备打开失败");            }        }    }
第二步:按下按钮搜索蓝牙设备    @Override    public void onClick(View v) {        if (!mBluetoothAdapter.isDiscovering()) {            mBluetoothAdapter.startDiscovery();            setProgressBarIndeterminateVisibility(true);        }    }//广播接收器接收设备并保存刷新    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            // 扫描到新的蓝牙设备            if (BluetoothDevice.ACTION_FOUND.equals(action)) {                // 获得蓝牙设备对象                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);                //防止设备对象添加重复                if (mDeviceList.contains(device)) {                    return;                }                mArrayAdapter.add(device.getName());                System.out.println(device.getName());                mDeviceList.add(device);                adapter.notifyDataSetChanged();            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {                // 扫描完成,关闭显示进度条                setProgressBarIndeterminateVisibility(false);            }            if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);                Toast.makeText(getApplicationContext(), "蓝牙已连接", Toast.LENGTH_SHORT).show();            } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);                Toast.makeText(getApplicationContext(), "蓝牙连接断开", Toast.LENGTH_SHORT).show();                String name = mDeviceList.get(devicePosition).getName() ;                mArrayAdapter.remove(devicePosition);                mArrayAdapter.add(devicePosition, name);                adapter.notifyDataSetChanged();                        }        }    };
第三步:选项监听,点击蓝牙设备则进行连接    @Override    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {        connected(mDeviceList.get(position), position);    }    // UUID号,表示不同的数据协议    private final String UUID_STR = "00001101-0000-1000-8000-00805F9B34FB";    //连接指定蓝牙设备    private void connected(BluetoothDevice device, int position) {        BluetoothSocket mSocket;        BluetoothDevice mDevice;        BluetoothSocket tmp = null;        mDevice = device;        try {            tmp = device.createRfcommSocketToServiceRecord(UUID                    .fromString(UUID_STR));            //   Toast.makeText(getApplicationContext(), "开始连接", Toast.LENGTH_SHORT).show();        } catch (IOException e) {            Toast.makeText(getApplicationContext(), "蓝牙连接失败", Toast.LENGTH_SHORT).show();        }        mSocket = tmp;        // 取消设备扫描        mBluetoothAdapter.cancelDiscovery();        try {            // 连接远程服务器设备            mSocket.connect();            //修改设备显示名字            String name = mDeviceList.get(position).getName() + "\t 已连接";            devicePosition = position;            mArrayAdapter.remove(position);            mArrayAdapter.add(position, name);            adapter.notifyDataSetChanged();            // Toast.makeText(MainActivity.this, "蓝牙连接成功", Toast.LENGTH_SHORT).show();        } catch (IOException connectException) {            Toast.makeText(MainActivity.this, "蓝牙连接失败", Toast.LENGTH_SHORT).show();            try {                mSocket.close();            } catch (IOException closeException) {            }        }    }下面那张图片是最终连接上的显示效果。我是先学习一个蓝牙聊天程序后自己打的上面代码。下面分析两个下载链接:第一个是本次实例的代码,第二个是那个蓝牙聊天项目的视频教程和对应源代码(建议先看视频,视频很详细的介绍了蓝牙的使用代码,保证看完后,对蓝牙的使用就too easy)

资料过大,我设置成百度云链接

本例代码:

http://download.csdn.net/download/mr_wilson_liu/10152685

蓝牙聊天项目的视频教程和对应源代码(为百度云下载链接):

http://download.csdn.net/download/mr_wilson_liu/10152681

原创粉丝点击