Bluetooth客户端与服务端

//蓝牙连接规范
private UUID uuid = UUID.fromString(“00001106-0000-1000-8000-00805F9B34FB”);
注意:
在服务端接收数据时会遇到
java.io.IOException: bt socket closed, read return: -1
这是因为服务端的read是阻塞方法 即使发送过去的文件读完了 也不会自己结束 只能走到0而不是-1
所以我们要先发送一个长度过去 服务端就可以通过这个长度来 判断是不是读完了 然后再自己break关闭

Bluetooth客户端:

BluetoothDevice device = list2.get(position);
//开启线程发送
//参数一:对应的蓝牙设备 
//参数二:(我这里是直接传一个json串过去) 随意
new ClientThread(MainActivity.this,device,"https://gitee.com/little_bird_oh_777/test_data_collection/raw/master/test42018061001.json").start();

//客户端线程

public class ClientThread extends Thread{
    private String url;
    private String path;
    private String name;
    private Handler handler;

    public ClientThread(String url, String path, String name, Handler handler) {
        this.url = url;
        this.path = path;
        this.name = name;
        this.handler = handler;
    }

    @Override
    public void run() {
    	   //最好用文件的泛型
        OkGo.<File>get(url)
                .execute(new FileCallback(path,name) {
                    @Override
                    public void onSuccess(Response<File> response) {
                        Log.i("TAG","下载完成");
                    }
				
                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);
                        //发送进度
                        float fraction = progress.fraction;
                        Message obtain = Message.obtain();
                        obtain.what = 101;
                        obtain.arg1 = (int)fraction;
                    }
                });
    }
}

//服务端
我推荐在开启蓝牙以后启动

//开启蓝牙
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
startActivity(intent);

//开启服务器
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            //通过适配器获取serverSocket对象
            BluetoothServerSocket serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(adapter.getName(), uuid);
            //死循环不断接收连接
            while(true){
                //服务器接受客户端连接
                BluetoothSocket socket = serverSocket.accept();
                Log.i("TAG",socket+"连接进来了");
                //启动服务器线程接受客户端发来的消息
                new ServerThread(socket,MainActivity.this).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();

服务端线程

class ServerThread extends Thread{
    private BluetoothSocket socket;
    private Activity context;

    public ServerThread(BluetoothSocket socket, Activity context) {
        this.socket = socket;
        this.context = context;
    }

    @Override
    public void run() {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("TAG","有人要给我发数据");
                Toast.makeText(context, "有人要给我发数据", Toast.LENGTH_SHORT).show();
            }
        });
        InputStream inputStream = null;
        StringBuffer sb = new StringBuffer();
        try {
            inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            //先读取发送过来的长度 
            //这里是因为我把长度和内容分开两次发 中间线程睡了一会将两段内容分开了 所以可以读取两次
            int read = inputStream.read(bytes);
            String s1 = new String(bytes, 0, read);
            
            //强转
            int i = Integer.parseInt(s1);
            //判断长度
            int count = 0;
            //读取内容
            while((len = inputStream.read(bytes))!=-1){
                //没下一点 长度涨一点
                count+=len;
                sb.append(new String(bytes,0,len));
                //当发送过来的长度等于下载的长度时 结束
                if(count == i){
                    break;
                }

            }
            Log.i("TAG",sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(android)