android开发之蓝牙主动配对连接手机

上一篇介绍了手机配对连接的三种方式,这篇以完整的一个代码实例介绍如何搜索周围的蓝牙设备,以及主动配对,连接。package jason.com;import java.io.IOException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;import

大家好,又见面了,我是全栈君。

上一篇介绍了手机配对连接的三种方式,这篇以完整的一个代码实例介绍如何搜索周围的蓝牙设备,以及主动配对,连接。

主要注释在代码中都有。

package jason.com;

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表示串口服务
	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 jason0539 搜索jason0539进入我的博客
		/*
		 * 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();
			}
		}

	}
}

 

作者:jason0539

微博:http://weibo.com/2553717707

博客:http://blog.csdn.net/jason0539(转载请说明出处)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/121374.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 异或和左移的优先级_异或链表

    异或和左移的优先级_异或链表给定一个非负整数序列 a,初始长度为 N。有 M 个操作,有以下两种操作类型:A x:添加操作,表示在序列末尾添加一个数 x,序列的长度 N 增大 1。Q l r x:询问操作,你需要找到一个位置 p,满足 l≤p≤r,使得:a[p] xor a[p+1] xor … xor a[N] xor x 最大,输出这个最大值。输入格式第一行包含两个整数 N,M,含义如问题描述所示。第二行包含 N 个非负整数,表示初始的序列 A。接下来 M 行,每行描述一个操作,格式如题面所述。输出格式每个询问操

    2022年8月10日
    3
  • 常用的搜索引擎有哪些(公认最好的3种搜索引擎)「建议收藏」

    常用的搜索引擎有哪些(公认最好的3种搜索引擎)「建议收藏」搜索引擎无论工作还是生活都无法避免,哪个引擎更适合使用?接下来用最为常用的baidu,bing,google做个简单对比。首先用baidu以现在最火的‘深度学习’为关键字进行搜索。我的2K分辨率的显示器最后一行才能看到一些有用的信息,最常用的1080P分辨率第一页是不可能有正确结果了。深度学习百度搜索结果(广告有点儿多)微软的bing搜索引擎支持国内版和国际版,首先用国内版对‘深度学习’关键字进行搜索。bing搜索结果(质量还不错,无广告!)使用国际版对相同的‘深度学习’关键字

    2022年5月18日
    81
  • 笔记:基于DCNN的图像语义分割综述

    笔记:基于DCNN的图像语义分割综述写在前面:一篇魏云超博士的综述论文,完整题目为《基于DCNN的图像语义分割综述》,在这里选择性摘抄和理解,以加深自己印象,同时达到对近年来图像语义分割历史学习和了解的目的,博古才能通今!感兴趣的请根据自己情况找来完整文章阅读学习。 图像的语义分割是计算机视觉中重要的基本问题之一,其目标是对图像的每个像素点进行分类,将图像分割为若干个视觉上有意义的或感兴趣的区域,以利于后续的图像分析和视觉理解.…

    2022年5月22日
    31
  • branch_git fetch

    branch_git fetch问:Igoogledandreadmanyposts,butnonecouldmakemeunderstandthebranchdivergenceproblemyet.IfI’veremotetrackingbranch,Ioftengetintothefollowing:$gitstatus#Onbranch

    2025年7月23日
    0
  • linux上安装软件详细步骤(开关安装方法图解)

    软件安装及管理一.软件的类型二.Tar包安装、升级、卸载(必须会)三.RPM软件包安装及管理(必须会)四.脚本安装、升级、卸载五.SRPM包安装(知道就行,很少用)一.软件的类型1.软件是指计算机系统中的程序及其文档程序必须装入机器内部才能工作文档一般是给人看的,不一定装入机器软件是用户与硬件之间的接口界面系统软件和应用软件2.应用程序与系统命令的关系文件位置系统命令:…

    2022年4月16日
    53
  • Git常用命令

    Git常用命令Git常用命令

    2022年4月23日
    41

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号