Android开发中编写蓝牙相关功能的核心代码讲解
一.什么是蓝牙(Bluetooth)?
1.1 BuleTooth是目前使用最广泛的无线通信协议
1.2 主要针对短距离设备通讯(10m)
1.3 常用于连接耳机,鼠标和移动通讯设备等.
二.与蓝牙相关的API
2.1BluetoothAdapter:
代表了本地的蓝牙适配器
2.2BluetoothDevice
代表了一个远程的Bluetooth设备
三.扫描已经配对的蓝牙设备(1)
注:必须部署在真实手机上,模拟器无法实现
首先需要在AndroidManifest.xml声明蓝牙权限
<user-permissionandroid:name="android.permission.BLUETOOTH"/>
配对蓝牙需要手动操作:
1.打开设置-->无线网络-->蓝牙勾选开启
2.打开蓝牙设置 扫描周围已经开启的蓝牙设备(可以与自己的笔记本电脑进行配对),点击进行配对
电脑上会弹出提示窗口:添加设备
显示计算与设备之间的配对码,要求确认是否配对
手机上也会显示类似的提示.
四.扫描已经配对的蓝牙设备(2)
4.1获得BluetoothAdapter对象
4.2判断当前移动设备中是否拥有蓝牙
4.3判断当前移动设备中蓝牙是否已经打开
4.4得到所有已经配对的蓝牙设备对象
蓝牙配对实现的核心代码如下:
MainActivity:
importjava.util.Iterator;
importjava.util.Set;
importandroid.app.Activity;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothDevice;
importandroid.content.Intent;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
publicclassMainActivityextendsActivity{
privateButtonbutton=null;
/**Calledwhentheactivityisfirstcreated.*/
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button)findViewById(R.id.buttonId);
button.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
//获得BluetoothAdapter对象,该API是android2.0开始支持的
BluetoothAdapteradapter=BluetoothAdapter.getDefaultAdapter();
//adapter不等于null,说明本机有蓝牙设备
if(adapter!=null){
System.out.println("本机有蓝牙设备!");
//如果蓝牙设备未开启
if(!adapter.isEnabled()){
Intentintent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//请求开启蓝牙设备
startActivity(intent);
}
//获得已配对的远程蓝牙设备的集合
Set<BluetoothDevice>devices=adapter.getBondedDevices();
if(devices.size()>0){
for(Iterator<BluetoothDevice>it=devices.iterator();it.hasNext();){
BluetoothDevicedevice=(BluetoothDevice)it.next();
//打印出远程蓝牙设备的物理地址
System.out.println(device.getAddress());
}
}else{
System.out.println("还没有已配对的远程蓝牙设备!");
}
}else{
System.out.println("本机没有蓝牙设备!");
}
}
});
}
}
修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备
1.修改本机蓝牙设备的可见性
2.扫描周围可用的蓝牙设备
Eg:
一. 清单文件AdroidManifest.xml:
<?xmlversion="1.0"encoding="utf-8"?> <manifestxmlns:android="http://schemas.android.com/apk/res/android" package="com.se7en" android:versionCode="1" android:versionName="1.0"> <uses-sdkandroid:minSdkVersion="8"/> <applicationandroid:icon="@drawable/icon"android:label="@string/app_name"> <activityandroid:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> <uses-permissionandroid:name="android.permission.BLUETOOTH"/> <!-若需要管理蓝牙设备,如修改可见性,则需以下的权限-> <uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"/> </manifest>
二.布局文件:main.xml:
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/discoverButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="设置可见性"/> <Button android:id="@+id/scanButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="开始扫描"/> </LinearLayout>
三.MainActivity:
importandroid.app.Activity;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothDevice;
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.IntentFilter;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
publicclassMainActivityextendsActivity{
privateButtondiscoverButton=null;
privateButtonscanButton=null;
privateBluetoothAdapteradapter=null;
privateBluetoothReceiverbluetoothReceiver=null;
/**Calledwhentheactivityisfirstcreated.*/
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter=BluetoothAdapter.getDefaultAdapter();
discoverButton=(Button)findViewById(R.id.discoverButton);
scanButton=(Button)findViewById(R.id.scanButton);
//修改蓝牙设备的可见性
discoverButton.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewview){
IntentdiscoverIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//设置蓝牙可见性,500表示可见时间(单位:秒),当值大于300时默认为300
discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,500);
startActivity(discoverIntent);
}
});
scanButton.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
//开始扫描周围蓝牙设备,该方法是异步调用并以广播的机制返回,所以需要创建一个BroadcastReceiver来获取信息
adapter.startDiscovery();
}
});
//设定广播接收的filter
IntentFilterintentFilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
//创建蓝牙广播信息的receiver
bluetoothReceiver=newBluetoothReceiver();
//注册广播接收器
registerReceiver(bluetoothReceiver,intentFilter);
}
privateclassBluetoothReceiverextendsBroadcastReceiver{
@Override
publicvoidonReceive(Contextcontext,Intentintent){
//获得扫描到的远程蓝牙设备
BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getAddress());
}
}
}