安卓中蓝牙基本API使用

蓝牙特点:

短距离传输10米以内,低功耗。IEEE 802.15.1 标准

基本概念

配对:

尚不清楚如何用代码自动配对,一般都为手动配对,配对后双方记录各自信息并存储下来,配对相当于校验身份,但不建立连接。

可见性:

一个蓝牙设备启动蓝牙功能后,只能对周围保持可见一小段时间,然后就进入不可见状态。安卓中这个时间最长为300秒

权限:

安卓使用蓝牙功能一般涉及两个权限android.permission.BLUETOOTH,android.permission.BLUETOOTH_ADMIN

扫描发现设备:

安卓中扫描周围的设备比较耗时,每发现一个设备都会发出一个广播,结束扫描也发一个广播。

简单的实例代码:

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.util.Log;

public class BlueToothAct extends Activity {
	final String TAG = "BlueTooth";
	BluetoothAdapter bluetoothAdapter;
	BroadcastReceiver receiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		initial();
		// 注册广播接收器,处理找到蓝牙设备的事件
		IntentFilter intentFilter = new IntentFilter(
				BluetoothDevice.ACTION_FOUND);
		receiver = new BluetoothReceiver();
		registerReceiver(receiver, intentFilter);
	}

	@Override
	protected void onDestroy() {
		// 解注册
		unregisterReceiver(receiver);
		super.onDestroy();
	}

	private void initial() {
		// 获得本机蓝牙适配器的实例,为空则证明没有蓝牙硬件
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (bluetoothAdapter == null) {
			Log.e(TAG, "本机没有蓝牙设备");
		} else {// isEnabled判断蓝牙是否打开
			if (!bluetoothAdapter.isEnabled()) {
				// 用这个action来请求打开蓝牙
				Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivity(i);
			}
			// 用getBondedDevices获取已经配对过的设备集合
			Set<BluetoothDevice> btDevice = bluetoothAdapter.getBondedDevices();
			if (btDevice.size() != 0) {
				Iterator<BluetoothDevice> it = btDevice.iterator();
				while (it.hasNext()) {
					BluetoothDevice device = it.next();
					Log.d(TAG, device.getAddress() + device.getName());
				}
			}
			// 开始扫描设备周围可见的蓝牙设备,耗时12秒。每找到一个设备会发送广播,结束时也有广播事件
			bluetoothAdapter.startDiscovery();
			// 下面的代码打开更改蓝牙设备可见时间修改请求对话框,请求超过300秒以上仍相当于300秒
			Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(i);
		}
	}

	private class BluetoothReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 接到广播后,从intent中获取对应的设备
			BluetoothDevice device = intent
					.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			Log.d(TAG, device.getName() + device.getAddress());
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值