发送文件从Android其它蓝牙设备蓝牙、文件、设备、Android

2023-09-06 00:57:36 作者:踩到姑娘滴小蘑菇

我试图通过以下code TI发送文件,从机器人到其他设备

i am trying ti send file from android to another device by using the following code

        socket = device.createRfcommSocketToServiceRecord(uuid);
        socket.connect();
        OutputStream os = socket.getOutputStream();
        File f = new File(strPath);
        byte [] buffer = new byte[(int)f.length()];
        FileInputStream fis = new FileInputStream(f);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(buffer,0,buffer.length);
        os.write(buffer,0,buffer.length);
        os.flush();
        os.close();
        socket.close();

我添加蓝牙以及BLUETOOTH_ADMIN用户权限在AndroidManifest.xml中

I added BLUETOOTH and BLUETOOTH_ADMIN to user permissions in AndroidManifest.xml

但文件不会传输,连接建立B / W设备

But file is not transferring, connection is establishing b/w devices

推荐答案

我不知道为什么你的方式是行不通的,如果有人知道答案请发表我也想知道。但是,下面是我有我的工作,我基本上将文件发送1024字节的块。

I don't know why your way isn't working, if someone knows the answer please post I would like to know. But below is how I got mine to work, I'm basically sending the file in chunks of 1024 bytes.

/*Transmit*/
private OutputStream mOut;
byte[] mBuffer = byte[1024]
mBtSocket = _socket;
mOut = mBtSocket.getOutputStream();
InputStream inFile = new FileInputStream(file);
while((mLen = inFile.read(mBuffer, 0, 1024)) > 0){
         mOut.write(mBuffer, 0, mLen);
}

/*Receive*/
private InputStream mIn;
byte[] mBuffer = byte[1024]
File file = new File(fileName);
OutputStream outFile = new FileOutputStream(file);
long bytesReceived = 0;
while (bytesReceived < fileSize) {  // I send fileSize as msg prior to this file transmit
    mLen = mIn.read(mBuffer);
if(mLen > 0) {
    bytesReceived+=mLen;
    outFile.write(mBuffer, 0, mLen);
} else {
    Log.d(TAG,"Read received -1, breaking");
    break;
}
}
outFile.close();