小记BT配对及取消配对的应用程序源码,直接附上源码。

layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.bttest.MainActivity" ><TextView android:id="@+id/title_paired_devices"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="@string/title_paired_devices"android:visibility="gone"android:background="#666"android:textColor="#fff"android:paddingLeft="5dp"/><ListView android:id="@+id/paired_devices"android:layout_width="match_parent"android:layout_height="wrap_content"android:transcriptMode="alwaysScroll"android:layout_weight="1"/><TextView android:id="@+id/title_new_devices"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="@string/title_other_devices"android:visibility="gone"android:background="#666"android:textColor="#fff"android:paddingLeft="5dp"/><ListView android:id="@+id/new_devices"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:transcriptMode="alwaysScroll"/>
</LinearLayout>

layout/device_name.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source ProjectLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.
-->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="18sp"android:padding="5dp"
/>

menu/main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"tools:context="com.example.bttest.MainActivity" ><item android:id="@+id/scan_paired"android:icon="@android:drawable/ic_menu_search"android:title="@string/scan_paired"android:showAsAction="ifRoom|withText" /><item android:id="@+id/scan_new"android:icon="@android:drawable/ic_menu_mylocation"android:title="@string/scan_new"android:showAsAction="ifRoom|withText" />
</menu>

values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><string name="app_name">BtTest</string><string name="scan_paired">已配对的蓝牙设备</string><string name="none_found">No devices found</string><string name="scan_new">扫描新的蓝牙设备</string><string name="title_other_devices">Other Available Devices(click to pair)</string><string name="title_paired_devices">Paired Devices(click to unpair)</string><string name="bt_not_enabled_leaving">Bluetooth was not enabled!</string>
</resources>

MainActivity.java

package com.example.bttest;import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;public class MainActivity extends ActionBarActivity {private ArrayAdapter<String> mPairedDevicesArrayAdapter;private ArrayAdapter<String> mNewDevicesArrayAdapter;private BluetoothAdapter adapter;private static boolean clear_bt = false;private HashMap<String, BluetoothDevice> NewBtInfo = new HashMap<String, BluetoothDevice>();private HashMap<String, BluetoothDevice> PairedBtInfo = new HashMap<String, BluetoothDevice>();private static final int REQUEST_ENABLE_BT = 1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);adapter = BluetoothAdapter.getDefaultAdapter();// If the adapter is null, then Bluetooth is not supportedif (adapter == null) {Toast.makeText(this, "Bluetooth is not available",Toast.LENGTH_LONG).show();finish();return;}mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,R.layout.device_name);ListView pairedListView = (ListView) findViewById(R.id.paired_devices);pairedListView.setAdapter(mPairedDevicesArrayAdapter);pairedListView.setOnItemClickListener(mDeviceUnpairListener);mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,R.layout.device_name);ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);newDevicesListView.setAdapter(mNewDevicesArrayAdapter);newDevicesListView.setOnItemClickListener(mDevicePairListener);IntentFilter filter = new IntentFilter();filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);filter.addAction(BluetoothDevice.ACTION_FOUND);filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);registerReceiver(mReceiver, filter);// 调用isEnabled()方法判断当前蓝牙设备是否可用if (!adapter.isEnabled()) {// 如果蓝牙设备不可用的话,创建一个intent对象,该对象用于启动一个Activity,提示用户启动蓝牙适配器Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(intent, REQUEST_ENABLE_BT);}}// The on-click listener for all devices in the ListViewsprivate OnItemClickListener mDevicePairListener = new OnItemClickListener() {public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {String BtDeviceName = mNewDevicesArrayAdapter.getItem(arg2);BluetoothDevice BtDevice = NewBtInfo.get(BtDeviceName);try {// 开始配对,调用BluetoothDevice 的createBond()方法??Method m = BtDevice.getClass().getMethod("createBond",(Class[]) null);m.invoke(BtDevice, (Object[]) null);} catch (Throwable e) {Log.e("BTtest", "", e);}}};public void onActivityResult(int requestCode, int resultCode, Intent data) {switch (requestCode) {case REQUEST_ENABLE_BT:// When the request to enable Bluetooth returnsif (resultCode != Activity.RESULT_OK) {// User did not enable Bluetooth or an error occurredToast.makeText(this, R.string.bt_not_enabled_leaving,Toast.LENGTH_SHORT).show();finish();break;}}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.scan_paired) {scan_paired_bt();return true;}if (id == R.id.scan_new) {doDiscovery();return true;}return super.onOptionsItemSelected(item);}private void scan_paired_bt() {findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);System.out.println("本机拥有蓝牙设备");mPairedDevicesArrayAdapter.clear();PairedBtInfo.clear();// 得到所有已经配对的蓝牙适配器对象Set<BluetoothDevice> devices = adapter.getBondedDevices();if (devices.size() > 0) {// 用迭代for (Iterator<BluetoothDevice> iterator = devices.iterator(); iterator.hasNext();) {// 得到BluetoothDevice对象,也就是说得到配对的蓝牙适配器BluetoothDevice device = (BluetoothDevice) iterator.next();mPairedDevicesArrayAdapter.add(device.getName());PairedBtInfo.put(device.getName(), device);}}}private final BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();// When discovery finds a deviceif (BluetoothDevice.ACTION_FOUND.equals(action)) {if (clear_bt) {mNewDevicesArrayAdapter.clear();NewBtInfo.clear();clear_bt = false;}BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);// If it's already paired, skip it, because it's been listed// alreadyif (device.getBondState() != BluetoothDevice.BOND_BONDED) {mNewDevicesArrayAdapter.add(device.getName());NewBtInfo.put(device.getName(), device);}// When discovery is finished, change the Activity title} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {if (mNewDevicesArrayAdapter.getCount() == 0) {String noDevices = getResources().getText(R.string.none_found).toString();mNewDevicesArrayAdapter.add(noDevices);}} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {scan_paired_bt();}}};private void doDiscovery() {// Turn on sub-title for new devicesfindViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);// If we're already discovering, stop itif (adapter.isDiscovering()) {adapter.cancelDiscovery();}if (!clear_bt) {clear_bt = true;}// Request discover from BluetoothAdapteradapter.startDiscovery();}// The on-click listener for all devices in the ListViewsprivate OnItemClickListener mDeviceUnpairListener = new OnItemClickListener() {public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {String BtDeviceName = mPairedDevicesArrayAdapter.getItem(arg2);BluetoothDevice BtDevice = PairedBtInfo.get(BtDeviceName);unpairDevice(BtDevice);}};private void unpairDevice(BluetoothDevice device) {try {Method m = device.getClass().getMethod("removeBond", (Class[]) null);m.invoke(device, (Object[]) null);} catch (Exception e) {Log.e("unpair", e.getMessage());}}
}

BT配对/取消配对示例相关推荐

  1. Apple Watch教程|如何取消配对并抹掉 Apple Watch?

    取消配对 Apple Watch 后,它将恢复到出厂设置. 如果您正在 Apple Watch 上使用"钱包"App 中的交通卡,请先从 Apple Watch 中移除交通卡,然后 ...

  2. watch取消配对怎么重新配对_Apple Watch 怎么重新配对iphone手机

    展开全部 第一步.解除 Apple Watch 配对 1.首先可以在 iPhone 上打62616964757a686964616fe78988e69d8331333363373066开 Apple ...

  3. watch取消配对怎么重新配对_watch配对,apple watch 怎样取消配对后再重新配对

    提起watch配对,大家都知道,有人问apple watch 怎样取消配对后再重新配对,另外,还有人想问怎么将applewatch与手机匹配,你知道这是怎么回事?其实AppleWatch怎么重新配对i ...

  4. watch取消配对怎么重新配对_Apple Watch 怎么重新配对iphone手机?

    苹果在2015年4月正式发售了第一款 Apple Watch 手表,可以与 iPhone 配对,接收通知消息,打电话发消息等.有时候可能需要把当前的手表重新与 iPhone 进行配对,这里简单介绍下操 ...

  5. android 取消蓝牙配对框,android - 蓝牙配对 - 如何显示简单的取消/配对对话框? - 堆栈内存溢出...

    我在GitHub为这个问题准备了一个简单的测试项目 . 我正在尝试创建一个Android应用程序,它将从计算机屏幕扫描QR代码,然后使用数据(MAC地址和PIN或哈希)与蓝牙设备轻松配对(绑定). 类 ...

  6. 【Android】蓝牙开发——经典蓝牙:配对与解除配对 实现配对或连接时不弹出配对框

    目录 一.配对方法 二.解除配对方法 三.配对/解除配对结果 四.justwork配对模式下,不弹出配对框 五.pincode配对模式下,不弹出配对框 六.小结 在之前的文章[Android]蓝牙开发 ...

  7. watch取消配对怎么重新配对_苹果Apple Watch重新配对方法_Apple Watch怎么重新配对-硬件之家...

    相信大家都知道,苹果Apple Watch必须与手机比配才能进行完整的操作,那么当我们更换手机的时候,如何进行重新配对呢?这绝对是一个问题,相信好多人都在犯愁.不过不要紧,小编今天说的就是这个问题: ...

  8. android解除蓝牙的方法,如何在Android上以编程方式取消配对或删除配对的蓝牙设备?...

    这段代码对我有用 private void pairDevice(BluetoothDevice device) { try { if (D) Log.d(TAG, "Start Pairi ...

  9. php 舞伴配对,舞伴配对

    /* 舞伴配对问题 来舞蹈室的顺序: 男-姓名1:男-姓名2:女-姓名3:男-姓名4: 女-姓名5:男-姓名6:男-姓名7:女-姓名8: 最终配对顺序: 男1-女3:男2-女5:男4-女8:男:男: ...

最新文章

  1. 从数据集到2D和3D方法,一文概览目标检测领域进展
  2. 关于python中文处理
  3. qml 自定义消息框_Qt qml 自定义消息提示框
  4. php本地安装帝国视频,帝国cms如何播放视频
  5. TF-IDF(term frequency–inverse document frequency)
  6. python自学教程变量_Python学习入门基础教程(learning Python)--2.2.1 Python下的变量解析...
  7. 快手QoE指标设计的分析初探
  8. C++ STL--stack/queue 的使用方法
  9. 博学谷html css,博学谷 - CSS笔记12 - 清除浮动
  10. redis新数据类型-Geospatial
  11. POJ 3178 凸包+DP (巨坑)
  12. 实现gabor filter的滤波
  13. 挥发性有机物TVOC、VOC、VOCS气体检测+解决方案
  14. 「三楼总版主」葫芦侠创始人-流火
  15. 大学计算机专业课教师听课评语,教师听课评语
  16. 血淋淋的BUG:波音在软件开发上错在哪里?
  17. Java游戏项目之坦克大战
  18. 机器学习与网络安全(一)
  19. androidstudio图片居中_Android imageView图片按比例缩放-Fun言
  20. 5G的五项核心技术和5.5G相关的技术

热门文章

  1. CentOS 6.10安装Python2.7.15【全过程-含yum及pip问题处理】
  2. Android Studio无法下载
  3. AXI 总线协议学习笔记(4)
  4. 使用阿里云发送短信验证码(JAVA实现)
  5. 简单移动平均线(Simple Moving Average,SMA) 定义及使用
  6. 编译原理学习之语法分析
  7. AutoCAD VBA点抽稀程序
  8. DockWidget
  9. matlab与数字图像处理--图像锐化imsharpen
  10. ue编辑器(UltraEdit编辑器)将制表符(Tab键)替换成其竖线分隔符(其他分隔符)乱码