O(∩_∩)O哈哈~

来源:互联网 发布:c语言中读和写的区别 编辑:程序博客网 时间:2024/04/28 06:37

蓝牙通信文档

一、蓝牙客户端通信的基本步骤:

1.获取本地蓝牙适配器

 BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();

2.判断本地蓝牙是否开启

adapter.isEnabled();

(1)如果开启,进入步骤3;

(2)如果未开启,则开启蓝牙:

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivity(intent);

3.设置蓝牙可见性:只有设置蓝牙的可见性,蓝牙才能被周围其他设备搜索到(蓝牙的可见性最久为300秒,如果设置的值比300毫秒大,则会默认为300秒,如果设置的值比300秒小,则其可见性为设置的值)

Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,60);

4.获取已绑定的蓝牙(蓝牙是否打开、可见与获取已绑定的蓝牙无关)

Set<BluetoothDevice> devices=adapter.getBondedDevices();

5.遍历已绑定的蓝牙,查看是否有将要进行连接的设备

(1)如果没有则进行扫描周围的设备,步骤6

    (2)如果有则直接连接

 if(set.size()>0) {

 Iterator it=set.iterator();

 while(it.hasNext()){

    BluetoothDevice dd=(BluetoothDevice) it.next();

    String address=dd.getAddress();

    String name = dd.getName();

//连接远程设备

 }

}

6注册广播接收器并开始搜索周围设备,适配器进行的是异步搜索,每次搜索大约耗费12秒的时间,每扫描到一个设备,都会发送一个广播。(在广播接收器中处理扫描到的设备)

(1)//注册发现设备广播器

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

receiver = new Receiver();

registerReceiver(receiver, filter);

(2)//开始搜索

adapter.startDiscovery();

7.连接设备

(1)连接设备前先取消扫描adapter.cancelDiscovery();

(2)根据设备的Mac地址来连接设备

BluetoothDevice btDev = adapter.getRemoteDevice(device.getAddress());

8设备之间通信:(通过反射技术)

(1)获得Socket

Method m;

m = btDev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});

BluetoothSocket  btSocket = (BluetoothSocket) m.invoke(btDev, Integer.valueOf(1));

(2)Socket通信

//传输信息

(3)通信结束,关闭Socket 取消广播器注册消息

二、蓝牙服务器端的通信

 1首先使蓝牙设备一直处于开启状态,并且设置蓝牙设备一直处于可见性(和客户端开启蓝 牙、设置蓝牙可见性相同)

//得到adapter

 2 启动新的线程,监听客户端状态

  BluetoothServerSocket tmp=null;

  Method listenMethod;

  istenMethod=adapter.getClass().getMethod("listenUsingRfcommOn",newClass[]{int.class});

  tmp = ( BluetoothServerSocket) listenMethod.invoke(btAdapt, Integer.valueOf( 1));

  //获取Socket

  socket = tmp .accept();

  //开始通信

三、目前存在的问题

1.蓝牙连接的时候必须手动连接,服务器端如何“手动连接”

2.蓝牙设备必须设置可见性,才能被其他,但是蓝牙可见性只有300秒,如何让它一直处于可见性。

 

四、代码

package com.example.tt;

 

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.Set;

 

import android.app.Activity;

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;

import android.bluetooth.BluetoothSocket;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.ListView;

import android.widget.Toast;

 

public class MainActivity extends Activity {

Button search;

Receiver receiver;

BluetoothAdapter adapter;

ListView foundDevice;

List<String> listFound;

List<String> listBound;

ListView listDevice;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

adapter = BluetoothAdapter.getDefaultAdapter();

if(adapter==null) {

Toast.makeText(MainActivity.this,"本设备不支持蓝牙",Toast.LENGTH_SHORT).show();

return;

}else {

if(!adapter.isEnabled()) {

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivity(intent);

}

}

 IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

     IntentFilter notFound  = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

     receiver = new Receiver();

     registerReceiver(receiver, foundFilter);

     registerReceiver(receiver, notFound);

search = (Button) findViewById(R.id.search);

listBound = new ArrayList<String>();

listFound = new ArrayList<String>();

listDevice = (ListView) findViewById(R.id.listDevice);

foundDevice = (ListView) findViewById(R.id.foundDevice);

ItemClickListener itemListener = new ItemClickListener();

listDevice.setOnItemClickListener(itemListener);

foundDevice.setOnItemClickListener(itemListener);

showBonded();

Listener listener = new Listener();

search.setOnClickListener(listener);

}

 

 

private class Listener implements OnClickListener {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

if(v==search){

Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

        enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,100); //3600为蓝牙设备可见时间

        startActivity(enable);

        adapter.startDiscovery();

        Toast.makeText(MainActivity.this,"正在搜索中。。。。",Toast.LENGTH_LONG).show();

}

}

}

private class ItemClickListener implements OnItemClickListener{

 

@Override

public void onItemClick(AdapterView<?> parent, View view, int position,

long id) {

// TODO Auto-generated method stub

//点击则进行连接

ListView listView = (ListView)parent;

String list = (String) listView.getItemAtPosition(position);

Toast.makeText(MainActivity.this,"连接"+list+"设备",Toast.LENGTH_SHORT).show();

conn(list);

}

}

private class Receiver extends  BroadcastReceiver {

 

@Override

public void onReceive(Context context, Intent intent) {

 String action = intent.getAction();

 if (BluetoothDevice.ACTION_FOUND.equals(action)) {

             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

             // conn(device.getAddress());

             listFound.add(device.getAddress());

 }

if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

    Toast.makeText(MainActivity.this,"搜索结束",Toast.LENGTH_SHORT).show();

    unregisterReceiver(receiver);

    ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listFound);

foundDevice.setAdapter(arrayAdapter);

 }

}

}

 @Override

    protected void onDestroy() {

        unregisterReceiver(receiver);

        super.onDestroy();

    }

 public void showBonded(){

 Set<BluetoothDevice> set = adapter.getBondedDevices();

 Iterator<BluetoothDevice> it=set.iterator();

 if(set.size()>0) {

 while(it.hasNext()){

 BluetoothDevice bondDevice = (BluetoothDevice) it.next();

 listBound.add(bondDevice.getAddress());

 }

 ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listBound);

 listDevice.setAdapter(arrayAdapter);

 }else {

 Toast.makeText(MainActivity.this,"no bounded",Toast.LENGTH_SHORT).show();

 }

 

 }

 BluetoothSocket socket;

 public static int connNum = 0;

 public void conn(String address){

 adapter.cancelDiscovery();

 BluetoothDevice btDev = adapter.getRemoteDevice(address);

         //Toast.makeText(MainActivity.this,btDev.getAddress(),Toast.LENGTH_LONG).show();

         BluetoothSocket socket;

 try {

if(btDev!=null) {

socket = btDev.createRfcommSocketToServiceRecord(btDev.getUuids()[0].getUuid());

socket.connect();

Toast.makeText(MainActivity.this,"连接成功,可以进行通信",Toast.LENGTH_LONG).show();

communicate();

}else {

Toast.makeText(MainActivity.this,"连接失败,未找到设备",Toast.LENGTH_LONG).show();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

Toast.makeText(MainActivity.this,btDev.getUuids()[0].getUuid().toString(),Toast.LENGTH_LONG).show();

}

 }

 public void communicate() throws IOException{

 OutputStream  out = socket.getOutputStream();

  BufferedReader  reader = new BufferedReader(new FileReader(new File("/sdcard/Vlog.xml")));

  String singleLine =  null;

String[] binary =null;

StringBuilder  content  = new StringBuilder();

while((singleLine=reader.readLine())!=null&&!("".equals(singleLine))){

binary=singleLine.split(" ");

for(String word : binary){

int bin = Integer.parseInt(word,2);

content.append((char)bin).append(" ");

}

content.append(System.getProperty("line.separator"));

}

out.write(content.toString().getBytes());

Toast.makeText(MainActivity.this,content.toString(),Toast.LENGTH_LONG).show();

reader.close();

 }

 

}

 

0 0
原创粉丝点击