安卓蓝牙文件发送 [英] Android Bluetooth file sending

查看:15
本文介绍了安卓蓝牙文件发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过蓝牙在 Android 设备中发送文件.我已经完成了发现、连接并制作了一个蓝牙插座.问题是当我在蓝牙套接字的输出流中写入字节数组时,接收端没有收到任何东西,尽管它接受了正在发送的东西.

I am trying to send a file over bluetooth in an android device. I have done discovery, connection and have made a bluetooth socket. Problem is when i am writing the byte array in the output stream of the bluetooth socket, the recieving side does not receive anything although it accept that something is being sent.

这是我在做什么(蓝牙适配器不好)

Here's what Iam doing (bad is the bluetooth adaptor)

请指教.

try
    {
        BluetoothDevice dev = bad.getRemoteDevice(a);
        bad.cancelDiscovery();

        dev.createRfcommSocketToServiceRecord(new UUID(1111, 2222));
        Method m = dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        bs = (BluetoothSocket) m.invoke(dev, Integer.valueOf(1));
        bs.connect();
        tmpOut = bs.getOutputStream();
    }catch(Exception e)
    {

    }

    File f = new File(filename);

    byte b[] = new byte[(int) f.length()];
    try
    {
        FileInputStream fileInputStream = new FileInputStream(f);
        fileInputStream.read(b);
    }catch(IOException e)
    {
        Log.d(TAG, "Error converting file");
        Log.d(TAG, e.getMessage());
    }

    try {
        tmpOut.write(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

推荐答案

我正在使用以下代码片段连接到远程蓝牙设备中的串行服务,它对我来说工作正常.只需确保其他设备(可以是移动设备或 PC)具有用于通过蓝牙进行串行通信的服务器套接字(请参阅下面的服务器端代码)

I am using the below code snipped to connect to the serial service in a remote Bluetooth device and it is working fine for me. Just make sure that the other device (can be mobile or PC) has a server socket for serial communication over Bluetooth (see the server side code below)

客户端:

UUID serialUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice btDevice = btAdapter.getRemoteDevice(BTAddress); // Get the BTAddress after scan
BluetoothSocket btSocket = btDevice.createRfcommSocketToServiceRecord(SERIAL_UUID);
btSocket.connect();
InputStream iStream = btSocket.getInputStream();
OutputStream oStream = btSocket.getOutputStream();

服务器端:

UUID serialUUID = new UUID("1101", true);
String serviceURL = "btspp://localhost:" + serialUUID
        + ";name=Android BT Server;authorize=false;authenticate=false";
StreamConnectionNotifier connectionNotifier = (StreamConnectionNotifier) Connector
                        .open(serviceURL);
// Blocking method will wait for client to connect
StreamConnection connection = connectionNotifier.acceptAndOpen();

RemoteDevice remoteDevice = RemoteDevice.getRemoteDevice(connection);
InputStream btInput = connection.openInputStream();
OutputStream btOutput = connection.openOutputStream();

这篇关于安卓蓝牙文件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆