您的位置:首页 > 移动开发 > Android开发

android蓝牙开发——简单的文字传输

2016-05-11 23:07 881 查看
Android 蓝牙连接

BluetoothAdapter蓝牙适配器

BluetoothDevice 蓝牙设备

 

连接并实现通信过程

1.    打开蓝牙

//请求用户打开
Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler, RESULT_FIRST_USER);
//使蓝牙可见
Intent in = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);
startActivity(in);
//直接开启
//mBluetoothAdapter.enable();

 

2.    获取可配对或已经配对了的设备以及相关信息,包括名字,硬件地址。

private void findAvalibleDevice(){
//获取可配对蓝牙设备
Set<BluetoothDevice> device=mBluetoothAdapter.getBondedDevices();

if(mBluetoothAdapter!=null&&mBluetoothAdapter.isDiscovering()){
mList.clear();
mAdapter.notifyDataSetChanged();
}
if(device.size()>0){ //存在已经配对过的蓝牙设备
for(Iterator<BluetoothDevice> it=device.iterator();it.hasNext();){
BluetoothDevice btd=it.next();
mList.add(btd.getName()+'\n'+btd.getAddress());
mAdapter.notifyDataSetChanged();
}
}else{  //不存在已经配对过的蓝牙设备
mList.add("...");
mAdapter.notifyDataSetChanged();
}
}


蓝牙状态改变时会发送广播,设置一个广播监听器,可做相关操作

3.    创建socket连接

(1)连接时需要用到硬件地址device = mBluetoothAdapter.getRemoteDevice(address);
    (2)需要唯一的uuid

       Uuid 通用唯一识别码

socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));


(3)连接的时候需要分别客户端跟服务端,两个设备不能同时是客户端服务端。

4.通信

    getInptuStream() 获取输入流

getOutputStream()获取输出流

//接收
private class readThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;

try {
mmInStream = socket.getInputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
while (true) {
try {
if( (bytes = mmInStream.read(buffer)) > 0 )
{
byte[] buf_data = new byte[bytes];
for(int i=0; i<bytes; i++)
{
buf_data[i] = buffer[i];
}
String s = new String(buf_data);
Message msg = new Message();
msg.obj = s;
msg.what = 1;
LinkDetectedHandler.sendMessage(msg);
}
} catch (IOException e) {
try {
mmInStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
break;
}
}
}
}


 

//发送
private void sendMessageHandle(String msg)
{

try {
OutputStream os = socket.getOutputStream();
os.write(msg.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
注意:
测试需要两部手机。

参考:http://blog.csdn.net/gf771115/article/details/38236335
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 蓝牙