android 通过蓝牙和设备通信 收发数据

这边由于我不知道我们公司的设备代码怎么设计的,所以不太清楚通用性如何,不过一般而言应该差不多吧。

首先我自定义了一个蓝牙连接管理的类,初始化的参数为Activity的context(这里我写的很随意,理论上这个类写在Service中更好):

public class BTManager {
	private Context context = null;
	private BluetoothAdapter adapter = null;
	private BroadcastReceiver receiver = null;
	private BTService bts = null;

	// 初始化
	public BTManager(Context context) {
		this.context = context;
		initAdapter();
		initRecevier();
	}
}
首先判断手机支不支持蓝牙功能,如果支持则开启蓝牙

// 看是否支持蓝牙
private void initAdapter() {
	adapter = BluetoothAdapter.getDefaultAdapter();
	if (adapter == null) {
		Toast.makeText(context, "该设备不支持蓝牙!", Toast.LENGTH_SHORT).show();
		return;
	}
	enabledBT();
}

// 开启蓝牙
private void enabledBT() {
	if (!adapter.isEnabled()) {
		Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		context.startActivity(mIntent);
	}
}
然后初始化广播,这个广播是要给Acitivty注册的,用来通知界面蓝牙连接的状态:

// 初始化广播
private void initRecevier() {
	if(receiver == null){
		receiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String actionName = intent.getAction();
				if (actionName.equals("android.bluetooth.device.action.FOUND")) {
					// 获取找到设备的对象
					BluetoothDevice device = (BluetoothDevice) intent
							.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					
					// 如果找到的设备和想要搜索的设备名一致,就发送找到广播
					if (device.getName() != null
				
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值