android蓝牙主动发起配对实例
- package cn.madfinger.core;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.UUID;
- import android.app.Activity;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.ListView;
- import android.widget.Toast;
- import android.widget.ToggleButton;
- public class BlueToothTestActivity extends Activity {
- //该UUID表示串口服务
- //请参考文章<a href="http://wiley.iteye.com/blog/1179417">http://wiley.iteye.com/blog/1179417</a>
- static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
- Button btnSearch, btnDis, btnExit;
- ToggleButton tbtnSwitch;
- ListView lvBTDevices;
- ArrayAdapter<String> adtDevices;
- List<String> lstDevices = new ArrayList<String>();
- BluetoothAdapter btAdapt;
- public static BluetoothSocket btSocket;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // Button 设置
- btnSearch = (Button) this.findViewById(R.id.btnSearch);
- btnSearch.setOnClickListener(new ClickEvent());
- btnExit = (Button) this.findViewById(R.id.btnExit);
- btnExit.setOnClickListener(new ClickEvent());
- btnDis = (Button) this.findViewById(R.id.btnDis);
- btnDis.setOnClickListener(new ClickEvent());
- // ToogleButton设置
- tbtnSwitch = (ToggleButton) this.findViewById(R.id.tbtnSwitch);
- tbtnSwitch.setOnClickListener(new ClickEvent());
- // ListView及其数据源 适配器
- lvBTDevices = (ListView) this.findViewById(R.id.lvDevices);
- adtDevices = new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1, lstDevices);
- lvBTDevices.setAdapter(adtDevices);
- lvBTDevices.setOnItemClickListener(new ItemClickEvent());
- btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
- // ========================================================
- // modified by wiley
- /*
- * if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 读取蓝牙状态并显示
- * tbtnSwitch.setChecked(false); else if (btAdapt.getState() ==
- * BluetoothAdapter.STATE_ON) tbtnSwitch.setChecked(true);
- */
- if (btAdapt.isEnabled()) {
- tbtnSwitch.setChecked(false);
- } else {
- tbtnSwitch.setChecked(true);
- }
- // ============================================================
- // 注册Receiver来获取蓝牙设备相关的结果
- IntentFilter intent = new IntentFilter();
- intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
- intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
- intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
- intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
- registerReceiver(searchDevices, intent);
- }
- private BroadcastReceiver searchDevices = new BroadcastReceiver() {
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- Bundle b = intent.getExtras();
- Object[] lstName = b.keySet().toArray();
- // 显示所有收到的消息及其细节
- for (int i = 0; i < lstName.length; i++) {
- String keyName = lstName[i].toString();
- Log.e(keyName, String.valueOf(b.get(keyName)));
- }
- BluetoothDevice device = null;
- // 搜索设备时,取得设备的MAC地址
- if (BluetoothDevice.ACTION_FOUND.equals(action)) {
- device = intent
- .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- if (device.getBondState() == BluetoothDevice.BOND_NONE) {
- String str = "未配对|" + device.getName() + "|"
- + device.getAddress();
- if (lstDevices.indexOf(str) == -1)// 防止重复添加
- lstDevices.add(str); // 获取设备名称和mac地址
- adtDevices.notifyDataSetChanged();
- }
- }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
- device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- switch (device.getBondState()) {
- case BluetoothDevice.BOND_BONDING:
- Log.d("BlueToothTestActivity", "正在配对......");
- break;
- case BluetoothDevice.BOND_BONDED:
- Log.d("BlueToothTestActivity", "完成配对");
- connect(device);//连接设备
- break;
- case BluetoothDevice.BOND_NONE:
- Log.d("BlueToothTestActivity", "取消配对");
- default:
- break;
- }
- }
- }
- };
- @Override
- protected void onDestroy() {
- this.unregisterReceiver(searchDevices);
- super.onDestroy();
- android.os.Process.killProcess(android.os.Process.myPid());
- }
- class ItemClickEvent implements AdapterView.OnItemClickListener {
- @Override
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
- long arg3) {
- if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();
- String str = lstDevices.get(arg2);
- String[] values = str.split("\\|");
- String address = values[2];
- Log.e("address", values[2]);
- BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
- try {
- Boolean returnValue = false;
- if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
- //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
- Method createBondMethod = BluetoothDevice.class
- .getMethod("createBond");
- Log.d("BlueToothTestActivity", "开始配对");
- returnValue = (Boolean) createBondMethod.invoke(btDev);
- }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
- connect(btDev);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- private void connect(BluetoothDevice btDev) {
- UUID uuid = UUID.fromString(SPP_UUID);
- try {
- btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
- Log.d("BlueToothTestActivity", "开始连接...");
- btSocket.connect();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- class ClickEvent implements View.OnClickListener {
- @Override
- public void onClick(View v) {
- if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果
- {
- if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
- Toast.makeText(BlueToothTestActivity.this, "请先打开蓝牙", 1000)
- .show();
- return;
- }
- if (btAdapt.isDiscovering())
- btAdapt.cancelDiscovery();
- lstDevices.clear();
- Object[] lstDevice = btAdapt.getBondedDevices().toArray();
- for (int i = 0; i < lstDevice.length; i++) {
- BluetoothDevice device = (BluetoothDevice) lstDevice[i];
- String str = "已配对|" + device.getName() + "|"
- + device.getAddress();
- lstDevices.add(str); // 获取设备名称和mac地址
- adtDevices.notifyDataSetChanged();
- }
- setTitle("本机蓝牙地址:" + btAdapt.getAddress());
- btAdapt.startDiscovery();
- } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭
- if (tbtnSwitch.isChecked() == false)
- btAdapt.enable();
- else if (tbtnSwitch.isChecked() == true)
- btAdapt.disable();
- } else if (v == btnDis)// 本机可以被搜索
- {
- Intent discoverableIntent = new Intent(
- BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- discoverableIntent.putExtra(
- BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
- startActivity(discoverableIntent);
- } else if (v == btnExit) {
- try {
- if (btSocket != null)
- btSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- BlueToothTestActivity.this.finish();
- }
- }
- }
- }
android蓝牙主动发起配对实例的更多相关文章
- 如何实现android蓝牙开发 自动配对连接,并不弹出提示框
之前做一个android版的蓝牙 与血压计通讯的项目,遇到最大的难题就是自动配对. 上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了 我就 ...
- Android 蓝牙开发之搜索、配对、连接、通信大全
蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最 ...
- Android蓝牙实例(和单片机蓝牙模块通信)
最近做毕设,需要写一个简单的蓝牙APP进行交互,在网上也找了很多资料,终于给搞定了,这里分享一下^_^. 1.Android蓝牙编程 蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码 ...
- Android自己主动化測试之Monkeyrunner用法及实例
眼下android SDK里自带的现成的測试工具有monkey 和 monkeyrunner两个.大家别看这俩兄弟名字相像,但事实上是完全然全不同的两个工具,应用在不同的測试领域.总的来说,monke ...
- Android蓝牙自动配对Demo,亲测好使!!!
蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details ...
- Android蓝牙自动配对Demo,亲测好使!!!(转)
蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details ...
- Android 蓝牙开发(整理大全)
Android蓝牙开发 鉴于国内Android蓝牙开发的例子很少,以及蓝牙开发也比较少用到,所以找的资料不是很全. (一): 由于Android蓝牙的通信都需要用到UUID,如果由手机发起搜索,当搜索 ...
- Android蓝牙学习笔记
一 Bluetooth基本概念 蓝牙是无线数据和语音传输的开放式标准,它将各种通信设备.计算机及其终端设备.各种数字数据系统.甚至家用电器采用无线方式联接起来.它的传输距离为10cm-10m,如果增加 ...
- Android 蓝牙4.0 BLE
Android ble (Bluetooth Low Energy) 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用. BLE是蓝牙4.0的核心Profil ...
随机推荐
- js---10时间类
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- php实现简单算法3
php实现简单算法3 这篇文章主要介绍了PHP经典算法集锦,整理了各种常见的算法,包括排序.查找.遍历.运算等各种常见算法原理与实现技巧,需要的朋友可以参考下 1.首先来画个菱形玩玩,很多人学C时在书 ...
- RTSP传输协议之Methods总结
RTSP/1.0 200 OK Server: DSS/5.5.5 (Build/489.16; Platform/Linux; Release/Darwin; state/beta; ) Cseq: ...
- css3新特性选择器(补充)
1.选择p标签中的第一个字符 p:first-letter{ color:red; font-size:25px; } 2.选择p标签中的第一行 p:first-line{ color:red; fo ...
- 跨域使用onmessage实现方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 2017国家集训队作业[agc016e]Poor Turkey
2017国家集训队作业[agc016e]Poor Turkey 题意: 一开始有\(N\)只鸡是活着的,有\(M\)个时刻,每个时刻有两个数\(X_i,Y_i\),表示在第\(i\)个时刻在\(X_i ...
- 如何优雅的写UI——(5)选项卡功能实现
先在我们的选项卡可以说能用了,每个标签页都能点进去,但是这还远远没到能用的地步,比如说你把窗口最大化后. 立马就露出马脚了,所以这篇我们要先讲讲tabctrl的最基本的功能实现 改变选项卡大小 上图的 ...
- VPS搭建与IPv6使用教程
VPS搭建与IPv6使用教程 SoftEther命令: yum -y install gcc zlib-devel openssl-devel readline-devel ncurses-devel ...
- php实现遍历文件目录
php实现遍历文件目录 一.总结 1.熟悉简单:很经典的例子,多看,然后发现熟悉了很简单 二.php实现遍历目录 php实现遍历目录 代码一: //遍历目录 function iteral($path ...
- 2.Java实现基于SOAP的XML文档网络传输及远程过程调用(RPC)-
转自:https://blog.csdn.net/a214919447/article/details/55260411 SOAP(Simple Object Access Protocol,简单对象 ...