小米5s plus怎么root怎么官方root

蓝牙的搜索,配对,解除配对等 - 开源中国社区
当前访客身份:游客 [
当前位置:
发布于 日 14时,
&无详细内容&
代码片段(4)
蓝牙开发BluetoothDevelop.rar&~&1MB&&&&
MainActivity.java&~&12KB&&&&
package com.example.
import com.example.bluetoothdevelop.R;
import java.io.IOE
import java.lang.reflect.M
import java.util.ArrayL
import java.util.L
import java.util.S
import java.util.UUID;
import com.example.adapter.AgoblueToothA
import com.example.adapter.CanblueToothA
import android.app.A
import android.app.ActivityM
import android.app.ActivityManager.RunningServiceI
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.bluetooth.BluetoothS
import android.content.BroadcastR
import android.content.C
import android.content.I
import android.content.IntentF
import android.os.B
import android.os.H
import android.view.V
import android.widget.AdapterV
import android.widget.CheckB
import poundB
import android.widget.ImageV
import android.widget.LinearL
import android.widget.ListV
import android.widget.ProgressB
import android.widget.T
import poundButton.OnCheckedChangeL
public class MainActivity extends Activity implements
OnCheckedChangeListener {
static final String SPP_UUID = "0-805F9B34FB";
private BluetoothA
private CheckBox checkSwitchButton, bluetooth_on_
private Set&BluetoothDevice& agobluetoothD
private AgoblueToothA
private CanblueToothAdapter canA
private BluetoothD
private ListV
private ListV
private List&String& lstDevices = new ArrayList&String&();
private List&String& agoDevices = new ArrayList&String&();
private LinearLayout agolinear,
private ImageV
public static BluetoothSocket btS
private Boolean returnValue =
private Boolean isEnable =
private ProgressBar progressB
private Handler handler = new Handler();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initview();
initdata();
public void initdata() {
isEnable = this.getIntent().getBooleanExtra("bluetooth", false);
if (isEnable) {
Toast.makeText(this, "蓝牙处于开启状态",Toast.LENGTH_SHORT).show();
checkSwitchButton.setChecked(true);
Toast.makeText(this, "蓝牙处于关闭状态",Toast.LENGTH_SHORT).show();
* 初始化控件
public void initview() {
bluetooth = BluetoothAdapter.getDefaultAdapter();
checkSwitchButton = (CheckBox) findViewById(R.id.switch_bluetooth);
checkSwitchButton.setOnCheckedChangeListener(this);
bluetooth_on_off = (CheckBox) findViewById(R.id.bluetooth_on_of);
bluetooth_on_off.setOnCheckedChangeListener(this);
bluetooth_on_off.setOnClickListener(new ClickEvent());
canlinear = (LinearLayout) findViewById(R.id.linear_can);
agolinear = (LinearLayout) findViewById(R.id.linear_ago);
agolist = (ListView) agolinear
.findViewById(R.id.listview_blurtooth_agobluetooth);
canlinear = (LinearLayout) findViewById(R.id.linear_can);
canlist = (ListView) canlinear
.findViewById(R.id.listview_blurtooth_kepeidui);
imgsearch = (ImageView) findViewById(R.id.searchbluetooth);
imgsearch.setOnClickListener(new ClickEvent());
canAdapter = new CanblueToothAdapter(this, lstDevices);
canlist.setAdapter(canAdapter);
canlist.setOnItemClickListener(new CanItemClickEvent());
progressBar = (ProgressBar) findViewById(R.id.bluetooth_loading);
agoadapter = new AgoblueToothAdapter(this, agoDevices);
agolist.setAdapter(agoadapter);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注册广播接收器,接收并处理搜索结果
this.registerReceiver(searchDevices, intentFilter);
* 开启蓝牙
public void getbluetooth() {
if (!bluetooth.isEnabled()) {
Intent intent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
// 设置蓝牙可见性,最多300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(intent);
* 广播处理机制
private BroadcastReceiver searchDevices = 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 (device != null) {
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {// 搜索到的不是已经绑定的蓝牙设备
String str = device.getName() + "|"
+ device.getAddress();// 获取设备名称和mac地址
if (str != null && !str.equals("")) {
if (lstDevices.indexOf(str) == -1) {// 防止重复添加
lstDevices.add(str);
canlinear.setVisibility(View.VISIBLE);
canAdapter.notifyDataSetChanged();
canlinear.setVisibility(View.GONE);
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {// 连接状态改变的蓝牙
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String name = device.getName();
String str = device.getName() + "|" + device.getAddress();
if (device.getName().equalsIgnoreCase(name)) {
switch (device.getBondState()) {
case BluetoothDevice.BOND_BONDING:// 正在配对-11
case BluetoothDevice.BOND_BONDED:// 已配对-12
agoDevices.add(str);
agoadapter.notifyDataSetChanged();
agolinear.setVisibility(View.VISIBLE);
agolist.setVisibility(View.VISIBLE);
lstDevices.remove(str);
if (lstDevices.size() &= 0) {
canlinear.setVisibility(View.GONE);
canAdapter.notifyDataSetChanged();
case BluetoothDevice.BOND_NONE:// 未配对-10
agoDevices.remove(device.getName() + "|"
+ device.getAddress());
if (agoDevices.size() &= 0) {
agolinear.setVisibility(View.GONE);
agoadapter.notifyDataSetChanged();
if (lstDevices.indexOf(str) == -1) {
lstDevices.add(str);
canAdapter.notifyDataSetChanged();
} else if (action
.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
// progressBar.setVisibility(View.GONE);
protected void onDestroy() {
this.unregisterReceiver(searchDevices);
super.onDestroy();
* @author 点击事件
private class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
// 搜索蓝牙设备,在BroadcastReceiver显示结果
if (v == imgsearch) {
if (bluetooth.isEnabled()) {
Getbluetooth();
if (checkSwitchButton.isChecked()) {
Toast.makeText(MainActivity.this, "蓝牙未开启,请重新开启蓝牙开关",Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "请先打开蓝牙",Toast.LENGTH_SHORT).show();
} else if (v == bluetooth_on_off) {
if (bluetooth.isEnabled()) {
if (!bluetooth_on_off.isChecked()) {
bluetooth_on_off.setChecked(false);
bluetooth_on_off.setChecked(true);
if (checkSwitchButton.isChecked()) {
Toast.makeText(MainActivity.this, "蓝牙未开启,请重新开启蓝牙开关",Toast.LENGTH_SHORT).show();
bluetooth_on_off.setChecked(false);
Toast.makeText(MainActivity.this, "请先打开蓝牙",Toast.LENGTH_SHORT).show();
bluetooth_on_off.setChecked(false);
* 搜索蓝牙设备
public void Getbluetooth() {
if (bluetooth.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
Toast.makeText(MainActivity.this, "蓝牙未开启,请重新开启蓝牙开关",Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.VISIBLE);
handler.postDelayed(runnable, 21000);
if (bluetooth.isDiscovering()) {
bluetooth.cancelDiscovery();
lstDevices.clear();
agoDevices.clear();
agobluetoothDevices = bluetooth.getBondedDevices();// 已配对
System.out.println(agobluetoothDevices.size() + "==========");
if (agobluetoothDevices.size() & 0) {
Object[] lstDevice = agobluetoothDevices.toArray();
for (int i = 0; i & lstDevice. i++) {
device = (BluetoothDevice) lstDevice[i];
String str = device.getName() + "|" + device.getAddress();
if (agoDevices.indexOf(str) == -1)
agoDevices.add(str);
agoadapter.notifyDataSetChanged();
agolinear.setVisibility(View.VISIBLE);
agolist.setVisibility(View.VISIBLE);
agolinear.setVisibility(View.GONE);
agolist.setVisibility(View.GONE);
bluetooth.startDiscovery();
class CanItemClickEvent implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView&?& adapterView, View convertView,
int position, long parent) {
if (bluetooth.isDiscovering()) {
bluetooth.cancelDiscovery();
progressBar.setVisibility(View.GONE);
handler.removeCallbacks(runnable);
String str = lstDevices.get(position);
String[] values = str.split("\\|");
String address = values[1];
BluetoothDevice btDev = bluetooth.getRemoteDevice(address);
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) { // 未配对
// 利用反射方法调用BluetoothDevice.createBond(BluetoothDevice
// remoteDevice);
Toast.makeText(MainActivity.this,
"正在连接,请稍后...", 1000).show();
Method createBondMethod = BluetoothDevice.class
.getMethod("createBond");
returnValue = (Boolean) createBondMethod.invoke(btDev);
System.out.println(returnValue);
} catch (Exception e) {
e.printStackTrace();
class AgoItemClickEvent implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView&?& Viewgroup, View convertView,
int position, long parent) {
* 设备连接,此处蓝牙连接,连接之后,涉及到蓝牙通信,数据传输,但不是我的任务(。。。剩余代码不是我写的),代码就不贴出来了
* @param btDev
private void connect(BluetoothDevice btDev) {
UUID uuid = UUID.fromString(SPP_UUID);
btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
btSocket.connect();
} catch (IOException e) {
e.printStackTrace();
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.bluetooth_on_of:
if (isChecked) {
bluetooth_on_off
.setButtonDrawable(R.drawable.bluetooth_item_selector1);
bluetooth_on_off
.setButtonDrawable(R.drawable.bluetooth_item_selector2);
case R.id.switch_bluetooth:
if (isChecked) {
getbluetooth();
if (bluetooth.isEnabled()) {
Getbluetooth();
if(bluetooth.isEnabled()){
bluetooth.disable();
Toast.makeText(MainActivity.this,
"蓝牙已关闭", 1000).show();
bluetooth_on_off.setChecked(false);
progressBar.setVisibility(View.GONE);
handler.removeCallbacks(runnable);
lstDevices.clear();
agoDevices.clear();
agoadapter.notifyDataSetChanged();
canAdapter.notifyDataSetChanged();
canlinear.setVisibility(View.GONE);
agolinear.setVisibility(View.GONE);
Runnable runnable = new Runnable() {//计时
public void run() {
if (bluetooth.isDiscovering()) {
bluetooth.cancelDiscovery();
progressBar.setVisibility(View.GONE);
CanblueToothAdapter.java&~&2KB&&&&
package com.example.
import java.util.ArrayL
import java.util.L
import java.util.S
import com.example.bluetoothdevelop.R;
import android.bluetooth.BluetoothD
import android.content.C
import android.view.LayoutI
import android.view.V
import android.view.ViewG
import android.widget.BaseA
import android.widget.TextV
public class CanblueToothAdapter extends BaseAdapter{
private List&String& bluetoothDevices=new ArrayList&String&();
private LayoutI
public CanblueToothAdapter(Context context ,List&String& bluetoothDevices){
this.context=
this.inflater=LayoutInflater.from(context);
this.bluetoothDevices=bluetoothD
public int getCount() {
if (bluetoothDevices==null)
return bluetoothDevices.size();
public Object getItem(int position) {
return bluetoothDevices.get(position);
public long getItemId(int arg0) {
// TODO Auto-generated method stub
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
holder=new HolderView();
convertView=inflater.inflate(R.layout.canbluetooth_list_item, null);
holder.txtname=(TextView) convertView.findViewById(R.id.txt_canbluetooth_list_name);
convertView.setTag(holder);
holder=(HolderView) convertView.getTag();
String str=bluetoothDevices.get(position);
String[] values = str.split("\\|");
String list=values[0];
holder.txtname.setText(list);
return convertV
private class HolderView{
AgoblueToothAdapter.java&~&4KB&&&&
package com.example.
import java.lang.reflect.InvocationTargetE
import java.lang.reflect.M
import java.util.L
import com.example.bluetoothdevelop.R;
import android.app.AlertD
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.content.C
import android.content.DialogI
import android.view.LayoutI
import android.view.V
import android.view.View.OnClickL
import android.view.ViewG
import android.widget.BaseA
import android.widget.LinearL
import android.widget.TextV
public class AgoblueToothAdapter extends BaseAdapter {
private List&String& bluetoothD
private LayoutI
public AgoblueToothAdapter(Context context ,List&String& bluetoothDevices){
this.context=
this.inflater=LayoutInflater.from(context);
this.bluetoothDevices=bluetoothD
public int getCount() {
if (bluetoothDevices==null)
return bluetoothDevices.size();
public Object getItem(int position) {
return bluetoothDevices.get(position);
public long getItemId(int arg0) {
// TODO Auto-generated method stub
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView==null){
holder=new HolderView();
convertView=inflater.inflate(R.layout.agobluetooth_list_item, null);
holder.txtname=(TextView) convertView.findViewById(R.id.txt_agobluetooth_list_name);
holder.imgdelete= (LinearLayout) convertView.findViewById(R.id.img_bluetooth_delete);
holder.imgdelete.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
new AlertDialog.Builder(context)
.setTitle("温馨提示")
.setIcon(android.R.drawable.ic_dialog_info)
.setMessage("确认取消配对吗")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();
String str=bluetoothDevices.get(position);
String[] values = str.split("\\|");
String address=values[1];
BluetoothDevice bluetoothDevice=adapter.getRemoteDevice(address);
Method createBondMethod = BluetoothDevice.class.getMethod("removeBond");
isdelete = (Boolean) createBondMethod.invoke(bluetoothDevice);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(isdelete+"----------");
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();// 取消弹出框
}).create().show();
convertView.setTag(holder);
holder=(HolderView) convertView.getTag();
String str=bluetoothDevices.get(position);
String[] values = str.split("\\|");
String list=values[0];
holder.txtname.setText(list);
holder.imgdelete.setTag(str);
((ViewGroup) convertView)
.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
return convertV
public class HolderView{
public LinearL
开源中国-程序员在线工具:
相关的代码(1524)
写的 &相当的漂亮。
开源从代码分享开始
柠檬爱曾的其它代码经验578 米
在线时间6 小时
版本V8.1.6.0.MAACNDI
积分 599, 距离下一级还需 1401 积分
积分 599, 距离下一级还需 1401 积分
机型小米手机5
签到次数44
MIUI版本V8.1.6.0.MAACNDI
210028.jpg (195.88 KB, 下载次数: 0)
小米手环VS手环2
每天10点抢购了快2个月了,终于买到了,来个1+2的合影,
小米手环2来了,小米运动中解绑手环1,绑定手环2,
那旧的小米手环1给媳妇用,绑定到她的小米手机,却绑定不上,发现问题是因我的小米手机和手环1配对过(需要我的手机先关掉蓝牙连接),然后她的手机就可以连接上手环1了
问题来了:如何删除我的手机中蓝牙“已配对的设备”的小米手环1 呢? (不删除的话,在蓝牙连接范围内影响媳妇的手机连接手环1)
如下图:长按设备名称没有反应,进入连接界面也没有删除选项
162859.jpg (146.99 KB, 下载次数: 2)
蓝牙连接手环页面
分享到微信朋友圈
打开微信,点击底部的“发现”,使用 “扫一扫” 即可将网页分享到我的朋友圈。
经验578 米
在线时间6 小时
版本V8.1.6.0.MAACNDI
积分 599, 距离下一级还需 1401 积分
积分 599, 距离下一级还需 1401 积分
机型小米手机5
签到次数44
MIUI版本V8.1.6.0.MAACNDI
无人解答么&&
经验7846 米
在线时间1415 小时
版本7.6.20
机型小米Note 顶配版
签到次数233
MIUI版本7.6.20
通过手机发布
这是个问题啊
经验435 米
在线时间5 小时
版本6.12.8
积分 468, 距离下一级还需 32 积分
积分 468, 距离下一级还需 32 积分
机型小米Note 移动4G/联通4G
MIUI版本6.12.8
恢复手机出厂设置,目前只有这一种方法简单,还有一种比较危险,要用re文件管理器修改系统文件,要root权限,而且删错×了一个字,都可能卡白米,这里就不说了
经验578 米
在线时间6 小时
版本V8.1.6.0.MAACNDI
积分 599, 距离下一级还需 1401 积分
积分 599, 距离下一级还需 1401 积分
机型小米手机5
签到次数44
MIUI版本V8.1.6.0.MAACNDI
恢复手机出厂设置,目前只有这一种方法简单,还有一种比较危险,要用re文件管理器修改系统文件,要root权限 ...
昨天换了米5了,旧的米3双清了数据,问题解决了
经验455 米
在线时间5 小时
版本6.9.22
积分 458, 距离下一级还需 42 积分
积分 458, 距离下一级还需 42 积分
机型小米手机3-TD版
签到次数46
MIUI版本6.9.22
设置-更多连接-蓝牙 删除
经验931 米
在线时间12 小时
版本7.2.24
积分 874, 距离下一级还需 1126 积分
积分 874, 距离下一级还需 1126 积分
机型小米手机5S
签到次数90
MIUI版本7.2.24
进入“锁屏高级设置”,删除蓝牙解锁设备
在线时间0 小时
积分 22, 距离下一级还需 28 积分
积分 22, 距离下一级还需 28 积分
通过手机发布
关机半小时,开机进入蓝牙,删除即可
经验599 米
在线时间5 小时
版本V8.2.2.0.NAACNEB
积分 673, 距离下一级还需 1327 积分
积分 673, 距离下一级还需 1327 积分
机型小米手机5
MIUI版本V8.2.2.0.NAACNEB
在小米运动里解绑
经验1733 米
在线时间12 小时
版本V8.2.3.0.MBGCNDL
头像被屏蔽
机型小米手机5SPlus
MIUI版本V8.2.3.0.MBGCNDL
提示: 作者被禁止或删除 内容自动屏蔽
小米7周年勋章
2017米粉节晒单赢专属勋章
“澎湃S1 ”芯片纪念勋章
参与活动回帖可得
圣诞节勋章
参与圣诞活动
MIUI 300周
MIUI 300周更新纪念勋章
MIUI 3000万
MIUI 3000万发烧友纪念勋章
MIUI 7纪念勋章
MIUI 100周
100周发布纪念勋章
Copyright (C) 2017 MIUI
京ICP备号 | 京公网安备34号 | 京ICP证110507号上一篇: 下一篇:
相关资讯:
推荐单品:前言(android2.3版本,4.0版本由于是随机获取pin值,没有研究过):
1、蓝牙设备之间自动配对,需要两个设备都安装进行配对的apk(网上好多自动配对的帖子都没有说明情况)
2、在自动匹配的时候想通过反射调用BluetoothDevice的setPin、createBond、cancelPairingUserInput实现设置密钥、配对请求创建、取消密钥信息输入等。
1)createBond()创建,最终会调到源码的BluetoothService的createBond(String address)方法,通过对源码浅显的了解,createBond主要是写入匹配密钥(BluetoothService的writeDockPin())以及进入jni注册回调函数onCreatePairedDeviceResult观察匹配结果比如:
// Pins did not match, or remote device did not respond to pin
// request in time
// We rejected pairing, or the remote side rejected pairing. This
// happens if either side presses 'cancel' at the pairing dialog.
// Not sure if this happens
// Other device is not responding at all
// already bonded等,在jni中创建了进行匹配的device("CreatePairedDevice"),这时bluetooth会发送一个ACTION_PAIRING_REQUEST的广播,只有当前会出现密钥框的蓝牙设备收到。写完密钥之后,发送广播给另外一个蓝牙设备接收,然后打开密钥输入框进行匹配。
2)setPin()设置密钥,通过查看setting源码,发现在确认输入密钥之后会调用setPin()(如果点取消,就会调用cancelPairingUserInput,取消密钥框),setPin具体通过D-BUS做了什么没有去深究,但是在调用setPin的时候会remove掉一个map里面的键值对(address:int),也就是我们在调用setPin之后如果再去调用onCreatePairedDeviceResult,则该方法一定返回false,并且出现下面的打印提示:cancelUserInputNative(B8:FF:FE:55:EF:D6) called but no native data available, ignoring. Maybe the PasskeyAgent Request was already cancelled by the remote or by bluez.(因为该方法也会remove掉一个键值对)
3)cancelPairingUserInput()取消用户输入密钥框,个人觉得一般情况下不要和setPin(setPasskey、setPairingConfirmation、setRemoteOutOfBandData)一起用,这几个方法都会remove掉map里面的key:value(也就是互斥的)。
3、蓝牙耳机、手柄等一些无法手动配置的设备是如何完成自动配对的。
在源码里面有一个自动配对的方法,也就是把pin值自动设为“0000”
/*package*/ synchronized boolean attemptAutoPair(String address) {
if (!mBondState.hasAutoPairingFailed(address) &&
!mBondState.isAutoPairingBlacklisted(address)) {
mBondState.attempt(address);
setPin(address, BluetoothDevice.convertPinToBytes("0000"));
}该方法是在底层回调到java层的onRequestPinCode方法时被调用,首先 Check if its a dock(正常输入的密钥,走正常配对方式,双方输入匹配值),然后再 try 0000 once if the device looks dumb(涉及到Device.AUDIO_VIDEO相关部分如:耳机,免提等进入自动匹配模式)进行自动配对。 言归正传,虽然个人觉得自动配对需要双方乃至多方蓝牙设备都需要装上实现自动配对的apk,已经失去了自动配对的意义,但有可能还是会派上用场。下面我们看看现实情况的自动配对是什么样的吧。由于BluetoothDevice配对的方法都是hide的,所以我们需要通过反射调用被隐藏的方法,现在基本都是通用的工具类型了,网上模式基本一样。ClsUtils.javapackage cn.
import java.lang.reflect.F
import java.lang.reflect.M
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.util.L
public class ClsUtils
public static BluetoothDevice remoteDevice=
* 与设备配对 参考源码:platform/packages/apps/Settings.git
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
@SuppressWarnings("unchecked")
static public boolean createBond(@SuppressWarnings("rawtypes") Class btClass, BluetoothDevice btDevice)
throws Exception
Method createBondMethod = btClass.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
* 与设备解除配对 参考源码:platform/packages/apps/Settings.git
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
@SuppressWarnings("unchecked")
static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
throws Exception
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
@SuppressWarnings("unchecked")
static public boolean setPin(Class btClass, BluetoothDevice btDevice,
String str) throws Exception
Method removeBondMethod = btClass.getDeclaredMethod("setPin",
new Class[]
{byte[].class});
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,
new Object[]
{str.getBytes()});
Log.d("returnValue", "setPin is success " +btDevice.getAddress()+ returnValue.booleanValue());
catch (SecurityException e)
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
catch (IllegalArgumentException e)
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
catch (Exception e)
// TODO Auto-generated catch block
e.printStackTrace();
// 取消用户输入
@SuppressWarnings("unchecked")
static public boolean cancelPairingUserInput(Class btClass,
BluetoothDevice device)
throws Exception
Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
// cancelBondProcess()
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
Log.d("returnValue", "cancelPairingUserInput is success " + returnValue.booleanValue());
return returnValue.booleanValue();
// 取消配对
@SuppressWarnings("unchecked")
static public boolean cancelBondProcess(Class btClass,
BluetoothDevice device)
throws Exception
Method createBondMethod = btClass.getMethod("cancelBondProcess");
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
* @param clsShow
@SuppressWarnings("unchecked")
static public void printAllInform(Class clsShow)
// 取得所有方法
Method[] hideMethod = clsShow.getMethods();
int i = 0;
for (; i & hideMethod. i++)
//Log.e("method name", hideMethod.getName() + ";and the i is:"
// 取得所有常量
Field[] allFields = clsShow.getFields();
for (i = 0; i & allFields. i++)
//Log.e("Field name", allFields.getName());
catch (SecurityException e)
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
catch (IllegalArgumentException e)
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
catch (Exception e)
// TODO Auto-generated catch block
e.printStackTrace();
}Bluetooth1.java 主activity,所有界面操作实现地方 package cn.
import java.io.IOE
import java.util.ArrayL
import java.util.L
import android.app.A
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.bluetooth.BluetoothS
import android.content.BroadcastR
import android.content.C
import android.content.I
import android.content.IntentF
import android.os.B
import android.util.L
import android.view.M
import android.view.V
import android.widget.AdapterV
import android.widget.ArrayA
import android.widget.B
import android.widget.ListV
import android.widget.T
import android.widget.ToggleB
public class Bluetooth1 extends Activity {
/** Called when the activity is first created. */
Button btnSearch, btnDis, btnE
ToggleButton tbtnS
ListView lvBTD
ArrayAdapter&String& adtD
List&String& lstDevices = new ArrayList&String&();
BluetoothAdapter btA
public static BluetoothSocket btS
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);
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 final 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. i++) {
String keyName = lstName.toString();
Log.e(keyName, String.valueOf(b.get(keyName)));
BluetoothDevice device =
// 搜索设备时,取得设备的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", "正在配对......");
case BluetoothDevice.BOND_BONDED:
Log.d("BlueToothTestActivity", "完成配对");
//connect(device);//连接设备
case BluetoothDevice.BOND_NONE:
Log.d("BlueToothTestActivity", "取消配对");
protected void onDestroy() {
this.unregisterReceiver(searchDevices);
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
class ItemClickEvent implements AdapterView.OnItemClickListener {
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);
Boolean returnValue =
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
Toast.makeText(Bluetooth1.this, "远程设备发送蓝牙配对请求", 5000).show();
//这里只需要createBond就行了
ClsUtils.createBond(btDev.getClass(), btDev);
}else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
Toast.makeText(Bluetooth1.this, btDev.getBondState()+" ....正在连接..", 1000).show();
} catch (Exception e) {
e.printStackTrace();
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果
if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
Toast.makeText(Bluetooth1.this, "请先打开蓝牙", 1000)
if (btAdapt.isDiscovering())
btAdapt.cancelDiscovery();
lstDevices.clear();
Object[] lstDevice = btAdapt.getBondedDevices().toArray();
for (int i = 0; i & lstDevice. 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) {
if (btSocket != null)
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
Bluetooth1.this.finish();
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
}PairingRequest.java (重要部分,自动配对主要是这个部分完成,activity只是创建了一个配对请求) package cn.
import android.bluetooth.BluetoothD
import android.content.BroadcastR
import android.content.C
import android.content.I
import android.widget.T
public class PairingRequest extends BroadcastReceiver {
String strPsw = "0000";
final String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
static BluetoothDevice remoteDevice =
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_PAIRING_REQUEST)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
// ClsUtils.cancelPairingUserInput(device.getClass(),
// device); //一般调用不成功,前言里面讲解过了
Toast.makeText(context, "配对信息" + device.getName(), 5000)
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(context, "请求连接错误...", 1000).show();
// pair(device.getAddress(),strPsw);
}AndroidManifest.xml 启动activity,接收广播 &manifest xmlns:android="/apk/res/android"
package="cn.bluetooth"
android:versionCode="1"
android:versionName="1.0" &
android:minSdkVersion="8"
android:targetSdkVersion="15" /&
&uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /&
&uses-permission android:name="android.permission.BLUETOOTH" /&
&application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" &
android:name=".Bluetooth1"
android:label="@string/title_activity_bluetooth1" &
&intent-filter&
&action android:name="android.intent.action.MAIN" /&
&category android:name="android.intent.category.LAUNCHER" /&
&/intent-filter&
&/activity&
&receiver android:name=".PairingRequest"&
&intent-filter&
&action android:name="android.bluetooth.device.action.PAIRING_REQUEST" /&
&/intent-filter&
&/receiver&
&/application&
&/manifest&main.xml 布局 &LinearLayout xmlns:android="/apk/res/android"
xmlns:tools="/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" &
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnSearch"
android:text="btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnExit"
android:text="btnExit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnDis"
android:text="btnDis"
&ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tbtnSwitch"
android:text="tbtnSwitch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/lvDevices"
&/LinearLayout&我觉得想要真正意义上的完成蓝牙设备的自动配对,方法还是有的,需要研究一下setting部分的Bluetooth模块,以及根据蓝牙源码进行深入了解,期待着关于android bluetooth深入浅出的文章,大家有什么好的文章,留个言大家一起好好学习学习。 接受配对广播,然后设置pin,实现配对,但是网上的大部分手机是不可以的,android.bluetoothdevice 下 action_pair_request ,没有定义这个,开始困扰了我一点时间,实现难度:是否能进入那个广播响应。
定义了一个类,这个是网上的可以直接用//================================================================================================================================[java] view plainpackage zicox.
import java.lang.reflect.M
import java.lang.reflect.F
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.util.L
public class ClsUtils
* 与设备配对 参考源码:platform/packages/apps/Settings.git
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
static public boolean createBond(Class btClass, BluetoothDevice btDevice)
throws Exception
Method createBondMethod = btClass.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
* 与设备解除配对 参考源码:platform/packages/apps/Settings.git
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
throws Exception
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
static public boolean setPin(Class btClass, BluetoothDevice btDevice,
String str) throws Exception
Method removeBondMethod = btClass.getDeclaredMethod("setPin",
new Class[]
{byte[].class});
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,
new Object[]
{str.getBytes()});
Log.e("returnValue", "" + returnValue);
catch (SecurityException e)
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
catch (IllegalArgumentException e)
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
catch (Exception e)
// TODO Auto-generated catch block
e.printStackTrace();
// 取消用户输入
static public boolean cancelPairingUserInput(Class btClass,
BluetoothDevice device)
throws Exception
Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
// cancelBondProcess()
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
// 取消配对
static public boolean cancelBondProcess(Class btClass,
BluetoothDevice device)
throws Exception
Method createBondMethod = btClass.getMethod("cancelBondProcess");
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
* @param clsShow
static public void printAllInform(Class clsShow)
// 取得所有方法
Method[] hideMethod = clsShow.getMethods();
int i = 0;
for (; i & hideMethod. i++)
Log.e("method name", hideMethod[i].getName() + ";and the i is:"
// 取得所有常量
Field[] allFields = clsShow.getFields();
for (i = 0; i & allFields. i++)
Log.e("Field name", allFields[i].getName());
catch (SecurityException e)
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
catch (IllegalArgumentException e)
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
catch (Exception e)
// TODO Auto-generated catch block
e.printStackTrace();
static public boolean pair(String strAddr, String strPsw)
boolean result =
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
bluetoothAdapter.cancelDiscovery();
if (!bluetoothAdapter.isEnabled())
bluetoothAdapter.enable();
if (!BluetoothAdapter.checkBluetoothAddress(strAddr))
{ // 检查蓝牙地址是否有效
Log.d("mylog", "devAdd un effient!");
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
Log.d("mylog", "NOT BOND_BONDED");
ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
ClsUtils.createBond(device.getClass(), device);
remoteDevice = // 配对完毕就把这个设备对象传给全局的remoteDevice
catch (Exception e)
// TODO Auto-generated catch block
Log.d("mylog", "setPiN failed!");
e.printStackTrace();
Log.d("mylog", "HAS BOND_BONDED");
ClsUtils.createBond(device.getClass(), device);
ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
ClsUtils.createBond(device.getClass(), device);
remoteDevice = // 如果绑定成功,就直接把这个设备对象传给全局的remoteDevice
catch (Exception e)
// TODO Auto-generated catch block
Log.d("mylog", "setPiN failed!");
e.printStackTrace();
//================================================================================================================================ 还有一部分 activity//================================================================================================================================ [java] view plainpackage zicox.
import java.io.IOE
import java.io.UnsupportedEncodingE
import java.lang.reflect.M
import java.util.ArrayL
import java.util.L
import java.util.UUID;
import android.app.A
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.bluetooth.BluetoothS
import android.content.BroadcastR
import android.content.C
import android.content.I
import android.content.IntentF
import android.os.B
import android.util.L
import android.view.V
import android.widget.AdapterV
import android.widget.ArrayA
import android.widget.B
import android.widget.ListV
import android.widget.T
import android.widget.ToggleB
public class Demo_ad_escActivity extends Activity
//---------------------------------------------------
public static String ErrorM
Button btnSearch, btnDis, btnE
ToggleButton tbtnS
ListView lvBTD
ArrayAdapter&String& adtD
List&String& lstDevices = new ArrayList&String&();
BluetoothAdapter btA
public static BluetoothSocket btS
//---------------------------------------------------
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(!ListBluetoothDevice())finish();
Button Button1 = (Button) findViewById(R.id.button1);
ErrorMessage = "";
//---------------------------------------------------
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.toggleButton1);
tbtnSwitch.setOnClickListener(new ClickEvent());
// ListView及其数据源 适配器
lvBTDevices = (ListView) this.findViewById(R.id.listView1);
adtDevices = new ArrayAdapter&String&(this,
android.R.layout.simple_list_item_1, lstDevices);
lvBTDevices.setAdapter(adtDevices);
lvBTDevices.setOnItemClickListener(new ItemClickEvent());
btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
if (btAdapt.isEnabled())
tbtnSwitch.setChecked(false);
tbtnSwitch.setChecked(true);
// 注册Receiver来获取蓝牙设备相关的结果
String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(ACTION_PAIRING_REQUEST);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intent);
Button1.setOnClickListener(new Button.OnClickListener()
public void onClick(View arg0)
Print1(SelectedBDAddress);
//---------------------------------------------------
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. i++) {
String keyName = lstName[i].toString();
Log.e(keyName, String.valueOf(b.get(keyName)));
BluetoothDevice device =
// 搜索设备时,取得设备的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();
ClsUtils.setPin(device.getClass(),device,"0000");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
ClsUtils.cancelPairingUserInput(device.getClass(), device);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}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", "正在配对......");
case BluetoothDevice.BOND_BONDED:
Log.d("BlueToothTestActivity", "完成配对");
connect(device);//连接设备
case BluetoothDevice.BOND_NONE:
Log.d("BlueToothTestActivity", "取消配对");
if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST"))
Log.e("tag", "ddd");
BluetoothDevice btDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234");
// device.setPin(pinBytes);
ClsUtils.setPin(btDevice.getClass(), btDevice, "0000"); // 手机和蓝牙采集器配对
ClsUtils.createBond(btDevice.getClass(), btDevice);
ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
catch (Exception e)
// TODO Auto-generated catch block
e.printStackTrace();
class ItemClickEvent implements AdapterView.OnItemClickListener {
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);
Boolean returnValue =
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
//利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
Log.d("BlueToothTestActivity", "开始配对");
returnValue = (Boolean) createBondMethod.invoke(btDev);
ClsUtils.pair(address, "0000");
showMessage("here");
}else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
connect(btDev);
} catch (Exception e) {
e.printStackTrace();
private void connect(BluetoothDevice btDev) {
final UUID SPP_UUID = UUID.fromString("0-805F9B34FB");
UUID uuid = SPP_UUID;
btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
Log.d("BlueToothTestActivity", "开始连接...");
btSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果
if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
Toast.makeText(Demo_ad_escActivity.this, "请先打开蓝牙", 1000).show();
if (btAdapt.isDiscovering())
btAdapt.cancelDiscovery();
lstDevices.clear();
Object[] lstDevice = btAdapt.getBondedDevices().toArray();
for (int i = 0; i & lstDevice. 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) {
if (btSocket != null)
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
Demo_ad_escActivity.this.finish();
protected void onDestroy() {
this.unregisterReceiver(searchDevices);
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
public void showMessage(String str)
Toast.makeText(this,str, Toast.LENGTH_LONG).show();
如果您想留下此文,您可以将其发送至您的邮箱(将同时以邮件内容&PDF形式发送)
相关文章推荐
(Ctrl+Enter提交) &&
已有0人在此发表见解
&在& 18:54收藏到了
&&在信息爆炸的时代,您的知识需要整理,沉淀,积累!Lai18为您提供一个简单实用的文章整理收藏工具,在这里您可以收藏对您有用的技术文章,自由分门别类,在整理的过程中,用心梳理自己的知识!相信,用不了多久,您收藏整理的文章将是您一生的知识宝库!
· 蜀ICP备号-1

我要回帖

更多关于 小米5s怎么完全root 的文章

 

随机推荐