Android开发 您所在的位置:网站首页 请求配对访问通讯录 Android开发

Android开发

2024-06-10 02:38| 来源: 网络整理| 查看: 265

Android开发——蓝牙通信实现 项目需求项目主要代码及功能实现AndroidManifest.xmlres/values/string.xmlactivity_main.xmlChatServiceres/menu/option_menu.xmldevice_list.xmlDeviceListBlueToothChat 项目结果展示源码地址

项目需求

运用蓝牙进程通信,实现两个手机的蓝牙进行通信聊天。

项目主要代码及功能实现 AndroidManifest.xml

给予项目蓝牙通信的相关权限

res/values/string.xml

添加程序运行过程中的状态描述文本及配色代码等

蓝牙Demo 发送 你没有链接一个设备 蓝牙不可用,离开聊天室 链接中... 连接到: 无链接 蓝牙设备搜索中... 选择一个好友链接 没有配对好友 附近没有发现好友 已配对好友 其它可连接好友 搜索好友 我的好友 设置在线 退出 开始聊天 结束聊天 activity_main.xml

添加1个Toolbar控件,其内包含2个水平的TextView控件;在Toolbar控件的下方添加1个ListView控件,用于显示聊天内容;最后在ListView控件的下方添加水平放置的1个EditText控件和一个Button控件

tools:context=".MainActivity"> ChatService

创建一个ChatService的java文件,作为工具类 部分代码如下: 构建蓝牙对象

//构造方法,接收UI主线程传递的对象 public ChatService(Context context, Handler handler) { //构造方法完成蓝牙对象的创建 mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mHandler = handler; }

取消 CONNECTING 和 CONNECTED 状态下的相关线程,然后运行新的 mConnectThread 线程

public synchronized void connect(BluetoothDevice device) { if (mState == STATE_CONNECTING) { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } mConnectThread = new ConnectThread(device); mConnectThread.start(); setState(STATE_CONNECTING); }

开启一个 ConnectedThread 来管理对应的当前连接。之前先取消任意现存的 mConnectThread 、mConnectedThread 、 mAcceptThread 线程,然后开启新 mConnectedThread ,传入当前刚刚接受的socket 连接。最后通过 Handler来通知UI连接

public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } if (mAcceptThread != null) { mAcceptThread.cancel(); mAcceptThread = null; } mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(BluetoothChat.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); }

连接线程,专门用来对外发出连接对方蓝牙的请求和处理流程。构造函数里通过 BluetoothDevice.createRfcommSocketToServiceRecord() ,从待连接的 device 产生 BluetoothSocket. 然后在 run 方法中 connect ,成功后调用 BluetoothChatSevice 的 connected() 方法。定义 cancel() 在关闭线程时能够关闭相关socket 。

private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { e.printStackTrace(); } mmSocket = tmp; } @Override public void run() { setName("ConnectThread"); mAdapter.cancelDiscovery(); try { mmSocket.connect(); } catch (IOException e) { connectionFailed(); try { mmSocket.close(); } catch (IOException e2) { e.printStackTrace(); } ChatService.this.start(); return; } synchronized (ChatService.this) { mConnectThread = null; } connected(mmSocket, mmDevice); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } res/menu/option_menu.xml device_list.xml DeviceList

新建一个名为DeviceList的activity文件 本程序供菜单项主界面的选项菜单“我的友好”调用,用于:

显示已配对的好友列表;搜索可配对的好友进行配对新选择并配对的蓝牙设备将刷新好友列表注意:发现新的蓝牙设备并请求配对时,需要对应接受关键技术:动态注册一个广播接收者,处理蓝牙设备扫描的结果 部分代码如下: 定义广播接收者,用于处理扫描蓝牙设备后的结果 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override 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 (device.getBondState() != BluetoothDevice.BOND_BONDED) { mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { if (mNewDevicesArrayAdapter.getCount() == 0) { String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); } } } };

活动界面:

private void init() { Button scanButton = findViewById(R.id.button_scan); scanButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Toast.makeText(DeviceList.this, R.string.scanning, Toast.LENGTH_LONG).show(); doDiscovery(); //搜索蓝牙设备 } }); mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); //已配对蓝牙设备列表 ListView pairedListView =findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mPaireDeviceClickListener); //未配对蓝牙设备列表 ListView newDevicesListView = findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mNewDeviceClickListener); //动态注册广播接收者 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(mReceiver, filter); mBtAdapter = BluetoothAdapter.getDefaultAdapter(); Set pairedDevices = mBtAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) { mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); } } BlueToothChat

将MainActivity重命名为BlueToothChat 检查蓝牙权限

public void checkBlePermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); } else { Log.i("tag","已申请权限"); } }

判断是否支持蓝牙,并打开蓝牙,获取到BluetoothAdapter之后,还需要判断是否支持蓝牙,以及蓝牙是否打开。如果没打开,需要让用户打开蓝牙:

private void checkBleDevice() { //首先获取BluetoothManager BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); //获取BluetoothAdapter if (bluetoothManager != null) { BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter(); if (mBluetoothAdapter != null) { if (!mBluetoothAdapter.isEnabled()) { //调用enable()方法直接打开蓝牙 if (!mBluetoothAdapter.enable()){ Log.i("tag","蓝牙打开失败"); } else{ Log.i("tag","蓝牙已打开"); } //该方法也可以打开蓝牙,但是会有一个很丑的弹窗,可以自行尝试一下 // Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(enableBtIntent); } } else { Log.i("tag","同意申请"); } } }

返回进入好友列表操作后的数回调方法

public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CONNECT_DEVICE: if (resultCode == Activity.RESULT_OK) { String address = data.getExtras().getString(DeviceList.EXTRA_DEVICE_ADDRESS); BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); mChatService.connect(device); } else if (resultCode == Activity.RESULT_CANCELED) { Toast.makeText(this, "未选择任何好友!", Toast.LENGTH_SHORT).show(); } break; case REQUEST_ENABLE_BT: if (resultCode == Activity.RESULT_OK) { setupChat(); } else { Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show(); finish(); } } } 项目结果展示

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

源码地址

https://gitee.com/liu_peilin/bluetooth-communication



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有