Bluetooth蓝牙Bluetooth蓝牙
提供的包android.bluetooth。蓝牙功能包:
BluetoothAdapter 蓝牙适配器(代表本地蓝牙适配器)
BluetoothClass 蓝牙类(主要包括服务和设备)
BluetoothClass.Device 蓝牙设备类
BluetoothClass.Device.Major 蓝牙设备管理
BluetoothClass.Service 有关蓝牙服务的类
BluetoothDevice 蓝牙设备(主要指远程蓝牙设备)
BluetoothServerSocket 监听蓝牙连...
Bluetooth蓝牙
提供的包android.bluetooth。蓝牙功能包:
BluetoothAdapter 蓝牙适配器(代
本地蓝牙适配器)
BluetoothClass 蓝牙类(主要包括服务和设备)
BluetoothClass.Device 蓝牙设备类
BluetoothClass.Device.Major 蓝牙设备管理
BluetoothClass.Service 有关蓝牙服务的类
BluetoothDevice 蓝牙设备(主要指远程蓝牙设备)
BluetoothServerSocket 监听蓝牙连接的类
BluetoothSocket 蓝牙连接类
首先设置权限:
其次,要使用蓝牙,首先需要获得蓝牙适配器,
BluetoothAdapter _bluetooth=BluetoothAdapter.getDefaultAdapter();//获得本地蓝牙适配器
如果要获得远程的蓝牙适配器需要使用BluetoothDevice类。
先定义两个常量
private static final int REQUEST_ENABLE = 0x1;
private static final int REQUEST_DISCOVERABLE = 0x2;
1,请求打开蓝牙:
Intent enabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler,REQUEST_ENABLE);
2,请求能够被搜索
Intent enabler=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(enabler,REQUEST_DISCOVERABLE);
BluetoothAdapter中的动作常量还有:
ACTION_DISCOVERY_FINISHED 已完成蓝牙搜索
ACTION_DISCOVERY_STARTED 已经开始搜索蓝牙设备
ACTION_LOCAL_NAME_CHANGED 更改蓝牙的名字
ACTION_REQUEST_DISCOVERABLE 请求能够被搜索
ACTION_REQUEST_ENABLE 请求启动蓝牙
ACTION_SCAN_MODE_CHANGED 扫描模式已改变
ACTION_STATE_CHANGED 状态已改变
3,打开蓝牙
_bluetooth.enable();
4,关闭蓝牙
_bluetooth.disable();
BluetoothAdapter中的常用方法:
cancelDiscovery 取消当前设备搜索的过程
checkBluetoothAddress 检查蓝牙地址是否正确 如"00:43:A8:23:10:F0" 字母字符必须是大写才有效
disable 关闭蓝牙适配器
enable 打开蓝牙适配器
getAddress 取得本地蓝牙设备的适配器地址
getDefaultAdapter 得到默认的蓝牙适配器
getName 得到蓝牙的名字
getRemoteDevice 取得指定蓝牙地址的BluetoothDevice对象
getScanMode 取得扫描模式
getState 得到状态
isDiscovering 是否允许被搜索
isEnabled 是否打开
setName 设置名字
startDiscovery 开始搜索
5,搜索蓝牙设备
BluetoothDevice实际上是一个蓝牙硬件地址薄,该类对象是不可改变的。其操作都是远程蓝牙硬件使用BluetoothAdapter来创建一个BluetoothDevice对象。
代码
8-22
public class DiscoveryActivity extends ListActivity
{
private Handler _handler=new Handler();
//取得默认的蓝牙适配器
private BluetoothAdapter _bluetooth=BluetoothAdapter.getDefaultAdapter();
//用来存储搜索到的蓝牙设备
private List
();
//是否完成搜索
private volatile boolean _discoveryFinished;
private Runnable _discoveryWorker=new Runnable() {
public void run() {
_bluetooth.startDiscovery();
for (;;)
{
if (_discoveryFinished)
{
break;
}
try {
Thread.sleep(100);
}
catch (InterruptedException e) {}
}
}
};
//接收器,当搜索蓝牙设备完成时调用
private BroadcastReceiver _foundReceiver=new BroadcastReceiver() {
public void onReceive(Context context,Intent intent)
{
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
_devices.add(device);
showDevices();
}
};
private BroadcastReceiver _discoveryReceiver=new BroadcastReceiver() {
public void onReceive(Context context,Intent intent)
{
unregisterReceiver(_foundReceiver);
unregisterReceiver(this);
_discoveryFinished=true;
}
};
protected void onCreate(Bundle saveInstance)
{
super.onCreate(..);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
setContentView(R.layout.discovery)l
//如果蓝牙适配器没有打开 则结束
if (!_bluetooth.isEnabled())
{
finish();
return;
}
//注册接收器
IntentFilter discoveryFilter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(_discoveryReceiver,discoveryFilter);
IntentFilter foundFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(_foundReceiver,foundFilter);
//显示一个对话框,正在搜索蓝牙设备
SamplesUtils.indeterminate(DiscoveryActivity.this,_handler,"Scanning...",_discoveryWorkder,new OnDismissListener() {
public void onDismiss(DialogInterface dialog)
{
for (;_bluetooth.isDiscovering();)
{
_bluetooth.cancelDiscovery();
}
_discoveryFinished=true;
}
},true);
}
//显示列表
protected void showDevice()
{
List list=new ArrayList();
for (int i=0,size=_devices.size();i adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
_handler.post(new Runnable() {
public void run() {
setListAdapter(adapter);
}
});
}
protected void onListItemClick(ListView l,View v,int pos,long id)
{
Intent result=new Intent();
result.putExtra(BluetoothDevice.EXTRA_DEVICE,_devices.get(pos));
setResult(RESULT_OK,result);
finish();
}
}
6,Socket服务端与客户端
注册蓝牙服务器:
private BluetoothAdapter _bluetooth=BluetoothAdapter.getDefaultAdapter();
private BluetoothServerSocket _serverSocket=bluetooth.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
注 意listenUsingRfcommWithServiceRecord方法返回一个蓝牙服务器对象,其参数 PROTOCOL_SCHEME_RFCOMM是一个String类型的自定义常量,代表蓝牙服务器的名称,而 UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666")是该蓝牙服务器的唯一标识UUID。 在客户端连接服务器时需要使用这个UUID。
接收请求:
BluetoothSocket socket=_serverSocket.accept();
if (socket!=null) {....}
_serverSocket.close();//关闭蓝牙服务器
代码清单8-23
public static final String PROTOCOL_SCHEME_L2CAP="bt12cap"; //btspp btgoep tcpobex
private Thread _serverWorker=new Thread() {
public void run() {
listen();
}
};
onCreate { _serverWorker.start();}
onDestroy { shutdownServer();}
finalize() throws Throwable { shutdownServer();}
private void shutdownServer() {
new Thread() {
public void run() {
_serverWorker.interrupt();
if (_serverSocket!=null) {
try {
_serverSocket.close();
} catch (IOException e) { Log.e(TAG,"",e); }
_serverSocket=null;
}
}
}.start();
}
protected void listen(){
try {
_serverSocket=bluetooth.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
final List lines=new ArrayList();
_handler.post(new Runnable() {
public void run() {
lines.add("server started...");
ArrayAdapter adapter=new ArrayAdapter(ServerSocketActivity.this,android.R.layout.simple_list_item_1,lines);
setListAdapter(adapter);
}
});
BluetoothSocket socket=_serverSocket.accept();
if (socket!=null) {
InputStream is=socket.getInputStream();
int read=-1;
final byte[] bytes=new byte[2048];
for (;(read=is.read(bytes))>-1;) {
final int count=read;
_handler.post(new Runnable() {
public void run() {
StringBuilder b=new StringBuilder();
for (int i=0;i0) {
b.append(' ');
}
String s=Integer.toHexString(bytes[i] & 0xFF);
if (s.length()<2) {
b.append('0');
}
b.append(s);
}
String s=b.toString();
lines.add(s);
ArrayAdapter adapter=new ArrayAdapter(ServerSocketActivity.this,android.R.layout.simple_list_item_1,lines);
setListAdapter(adapter);
}
});
}
}
} catch (IOException e) { Log.e(TAG,"",e);}
finally {}
}
}
客户端的连接代码:
代码清单8-24
public class ClientSocketActivity extends Activity
{
private static final String TAG=ClientSocketActivity.class.getSimpleName();
private static final int REQUEST_DISCOVERY=0x1;
private Handler _handler=new Handler();
private BluetoothAdapter _bluetooth=BluetoothAdapter.getDefaultAdapter();
provate void onCreate(...) {
super...
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
setContentView(R.layout.client_socket);
if (!_bluetooth.isEnabled()) {
finish();
return ;
}
Intent intent=new Intent(this,DiscoveryActivity.class);
//提示选择一个要连接的服务器
Toast.makeText(this,"select device to connect",Toast.LENGTH_SHORT).show();
startActivityForResult(intent,REQUEST_DISCOVERY);
}
//选择了服务器之后进行连接
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
if (requestCode != REQUEST_DISCOVERY) {
return;
}
if (resultCode !=RESULT_OK) {
return;
}
final BluetoothDevice device=data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
new Thread() {
public void run() {
connect(device);
}
}.start();
}
protected void connect(BluetoothDevice device) {
BluetoothSocket socket=null;
try {
//创建一个Socket连接:只需要服务器在注册时的UUID号
//socket=device.createRfcommSocketToServiceRecord(BluetoothProtocols.OBEX_OBJECT_PUSH_PROTOCOL_UUID);
socket=device.createRfcommSocketToServiceRecord(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
//连接
socket.connect();
} catch (IOException e) { Log.e(TAG,"",e);
} finally {
if (socket !=null ) {
try {
socket.close();
} catch (IOException e) {
Log.e(TAG,"",e);
}
}
}
}
}
本文档为【Bluetooth蓝牙】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。