代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Java
】
蓝牙的搜索,配对,解除配对等
作者:
柠檬爱曾
/ 发布于
2015/10/19
/
877
蓝牙的搜索,配对,解除配对
package com.example.bluetoothdevelop; import com.example.bluetoothdevelop.R; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import com.example.adapter.AgoblueToothAdapter; import com.example.adapter.CanblueToothAdapter; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; 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.os.Handler; import android.view.View; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener; public class MainActivity extends Activity implements OnCheckedChangeListener { static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; private BluetoothAdapter bluetooth; private CheckBox checkSwitchButton, bluetooth_on_off; private Set<BluetoothDevice> agobluetoothDevices; private AgoblueToothAdapter agoadapter; private CanblueToothAdapter canAdapter; private BluetoothDevice device; private ListView agolist; private ListView canlist; private List<String> lstDevices = new ArrayList<String>(); private List<String> agoDevices = new ArrayList<String>(); private LinearLayout agolinear, canlinear; private ImageView imgsearch; public static BluetoothSocket btSocket; private Boolean returnValue = false; private Boolean isEnable = false; private ProgressBar progressBar; private Handler handler = new Handler(); @Override 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); } else { 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(); } } } else { 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 break; 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); } else { canAdapter.notifyDataSetChanged(); } break; case BluetoothDevice.BOND_NONE:// 未配对-10 agoDevices.remove(device.getName() + "|" + device.getAddress()); if (agoDevices.size() <= 0) { agolinear.setVisibility(View.GONE); } else { agoadapter.notifyDataSetChanged(); } if (lstDevices.indexOf(str) == -1) { lstDevices.add(str); } canAdapter.notifyDataSetChanged(); default: break; } } else if (action .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { // progressBar.setVisibility(View.GONE); } } } }; @Override protected void onDestroy() { this.unregisterReceiver(searchDevices); super.onDestroy(); } /** * * @author 点击事件 */ private class ClickEvent implements View.OnClickListener { @Override public void onClick(View v) { // 搜索蓝牙设备,在BroadcastReceiver显示结果 if (v == imgsearch) { if (bluetooth.isEnabled()) { Getbluetooth(); } else { if (checkSwitchButton.isChecked()) { Toast.makeText(MainActivity.this, "蓝牙未开启,请重新开启蓝牙开关",Toast.LENGTH_SHORT).show(); } else { 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); } else { bluetooth_on_off.setChecked(true); } } else { if (checkSwitchButton.isChecked()) { Toast.makeText(MainActivity.this, "蓝牙未开启,请重新开启蓝牙开关",Toast.LENGTH_SHORT).show(); bluetooth_on_off.setChecked(false); } else { 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(); return; } 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.length; 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); } else { agolinear.setVisibility(View.GONE); agolist.setVisibility(View.GONE); } bluetooth.startDiscovery(); } class CanItemClickEvent implements AdapterView.OnItemClickListener { @Override 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); try { 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 { @Override public void onItemClick(AdapterView<?> Viewgroup, View convertView, int position, long parent) { } } /** * 设备连接,此处蓝牙连接,连接之后,涉及到蓝牙通信,数据传输,但不是我的任务(。。。剩余代码不是我写的),代码就不贴出来了 * @param btDev */ private void connect(BluetoothDevice btDev) { UUID uuid = UUID.fromString(SPP_UUID); try { btSocket = btDev.createRfcommSocketToServiceRecord(uuid); btSocket.connect(); } catch (IOException e) { e.printStackTrace(); } } @Override 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); } else { bluetooth_on_off .setButtonDrawable(R.drawable.bluetooth_item_selector2); } break; case R.id.switch_bluetooth: if (isChecked) { getbluetooth(); if (bluetooth.isEnabled()) { Getbluetooth(); } } else { 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); } break; default: break; } } Runnable runnable = new Runnable() {//计时 @Override public void run() { if (bluetooth.isDiscovering()) { bluetooth.cancelDiscovery(); } progressBar.setVisibility(View.GONE); } }; private Intent service; CanblueToothAdapter.java package com.example.adapter; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.example.bluetoothdevelop.R; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class CanblueToothAdapter extends BaseAdapter{ private List<String> bluetoothDevices=new ArrayList<String>(); private Context context; private LayoutInflater inflater; public CanblueToothAdapter(Context context ,List<String> bluetoothDevices){ this.context=context; this.inflater=LayoutInflater.from(context); this.bluetoothDevices=bluetoothDevices; } @Override public int getCount() { if (bluetoothDevices==null) return 0; else return bluetoothDevices.size(); } @Override public Object getItem(int position) { return bluetoothDevices.get(position); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { HolderView holder; 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); }else{ holder=(HolderView) convertView.getTag(); } String str=bluetoothDevices.get(position); String[] values = str.split("\\|"); String list=values[0]; holder.txtname.setText(list); return convertView; } private class HolderView{ TextView txtname; } } AgoblueToothAdapter.java package com.example.adapter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import com.example.bluetoothdevelop.R; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class AgoblueToothAdapter extends BaseAdapter { private List<String> bluetoothDevices; private Context context; private LayoutInflater inflater; private boolean isdelete; public AgoblueToothAdapter(Context context ,List<String> bluetoothDevices){ this.context=context; this.inflater=LayoutInflater.from(context); this.bluetoothDevices=bluetoothDevices; } @Override public int getCount() { if (bluetoothDevices==null) return 0; else return bluetoothDevices.size(); } @Override public Object getItem(int position) { return bluetoothDevices.get(position); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { HolderView holder; 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() { @Override public void onClick(View arg0) { new AlertDialog.Builder(context) .setTitle("温馨提示") .setIcon(android.R.drawable.ic_dialog_info) .setMessage("确认取消配对吗") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override 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); try { 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); }else{ 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 convertView; } public class HolderView{ TextView txtname; public LinearLayout imgdelete; } }
试试其它关键字
蓝牙的搜索,配对,解除配对等
同语言下
.
List 切割成几份 工具类
.
一行一行读取txt的内容
.
Java PDF转换成图片并输出给前台展示
.
java 多线程框架
.
double类型如果小数点后为零则显示整数否则保留两位小
.
将图片转换为Base64字符串公共类抽取
.
sqlParser 处理SQL(增删改查) 替换schema 用于多租户
.
JAVA 月份中的第几周处理 1-7属于第一周 依次类推 29-
.
java计算两个经纬度之间的距离
.
输入时间参数计算年龄
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
柠檬爱曾
贡献的其它代码
(
8
)
.
php简单异或运算
.
透明LCD时钟
.
计算年龄 精确到天
.
卡拉兹的猜想
.
mongodb操作
.
随机生成短信验证码
.
rsa加密
.
蓝牙的搜索,配对,解除配对等
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3