android - 从android发送文件到其他蓝牙设备

标签 android bluetooth

我正在尝试使用以下代码将文件从 android 发送到另一台设备

        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();

我在 AndroidManifest.xml 中添加了 BLUETOOTH 和 BLUETOOTH_ADMIN 到用户权限

但是文件没有传输,连接正在建立黑白设备

最佳答案

我不知道为什么你的方法不起作用,如果有人知道答案请发帖我想知道。但下面是我如何让我的工作,我基本上是以 1024 字节的 block 发送文件。

/*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();

关于android - 从android发送文件到其他蓝牙设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9188639/

相关文章:

java - 如何使用 WiFi Direct 打印文本文件

java - Butterknife 无法使用示例

ios - 是否可以自定义 iOS 中首次出现警报时的蓝牙消息

c++ - SetupDiEnumDeviceInterfaces 不返回我们的蓝牙设备的接口(interface)

java - 从主要 Activity 中打开多个 fragment

java - 在 Parse 上使用 Google+ 登录

iOS蓝牙后台模式

c++ - 在 android 内核开发 linux 中使用蓝牙

android - 连接耳机时在扬声器中播放声音

Android 应用程序兼容性 21 : All my textview are white