通过蓝牙发送/接收文件

时间:2019-11-04 12:59:52

标签: android android-bluetooth

如何发送/接收视频文件(通过Bluetooth聊天示例代码使用)? 使用Bluetooth SDK提供的Android聊天示例,我可以在配对设备之间发送消息,但是当我尝试使用相同的输入和输出流发送视频文件时,这表明无效标头错误。

我正在使用以下代码:

ChatService.java

   private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
      mmSocket = socket;
      InputStream tmpIn = null;
      OutputStream tmpOut = null;
      // Get the BluetoothSocket input and output streams
      try {
        tmpIn = SocketHolder.getBluetoothSocket().getInputStream();
        tmpOut = SocketHolder.getBluetoothSocket().getOutputStream();

        //SocketHolder.setInputStream();
       // SocketHolder.setOutputStream();
      } catch (Exception e) {
      }
      mmInStream = tmpIn;
      mmOutStream = tmpOut;
    }

    public void run() {
      byte[] buffer = new byte[1024];
      int bytes;
      // Keep listening to the InputStream while connected
      while (true) {
        try {
          // Read from the InputStream
          bytes = mmInStream.read(buffer);
          // Send the obtained bytes to the UI Activity
          mHandler.obtainMessage(ChatActivity.MESSAGE_READ, bytes, -1, buffer)
              .sendToTarget();

        } catch (IOException e) {
          connectionLost();
          break;
        }
      }
    }

    /**
     * Write to the connected OutStream.
     *
     * @param buffer The bytes to write
     */
    public void write(byte[] buffer) {
      System.out.println("writing video to receiver");
      try {
       mmOutStream.write(buffer);
        // Share the sent message back to the UI Activity
        mHandler.obtainMessage(ChatActivity.MESSAGE_WRITE, -1, -1, buffer)
            .sendToTarget();
      } catch (IOException e) {
        System.out.println("exception in writing:" + e.getMessage());
      }
      System.out.println("exiting write Byte[]");
    }

FileReceiver.java

    package com.example.bluetoothrecorder.java_codegeeks_approach.utils;

    import android.content.Context;
    import android.content.ContextWrapper;
    import android.os.AsyncTask;
    import android.os.Environment;
    import android.util.Log;
    import com.example.bluetoothrecorder.recording.RecorderActivity;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.OutputStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;



    public class FileReceiverTask extends AsyncTask {

    private static final String TAG = "===FileReceiverTask";

    InputStream inputStream;
    TaskUpdate taskUpdate;
    MetaData metaData;
    //String filePath;
    public FileReceiverTask(TaskUpdate taskUpdate) {
        Log.d(FileReceiverTask.TAG,"Object created");
        this.taskUpdate = taskUpdate;
        try {

            Log.d(FileReceiverTask.TAG,"trying to get inputStream");
            inputStream = SocketHolder.getBluetoothSocket().getInputStream();
            Log.d(FileReceiverTask.TAG,"obtained inputStream");

        } catch (Exception e) {
            Log.d(FileReceiverTask.TAG,"Failed to obtain input stream");
            Log.d(FileReceiverTask.TAG,e.toString());
        }

    }

    @Override
    protected Object doInBackground(Object[] objects) {
        taskUpdate.TaskStarted();
        if(!SocketHolder.getBluetoothSocket().isConnected()) {
            Log.d(FileReceiverTask.TAG,"Socket is closed... Can't perform file receiving Task...");
            return null;
        }

        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            metaData = (MetaData)objectInputStream.readObject();
            Log.d(FileReceiverTask.TAG," Variable value received : " + metaData.toString() );
            //objectInputStream.close();
              File file= getFileName(metaData.getFname());
            if(!file.exists()) {
                Log.d(FileReceiverTask.TAG, "File does not exist : " + file.getPath());
            }  else {
                Log.d(FileReceiverTask.TAG,"File already exists : " + file.getPath());
            }

            OutputStream outputStreamWriteToFile = new FileOutputStream(file);
            Log.d(FileReceiverTask.TAG,"outputStreamWriteToFile created");

            byte[] buffer = new byte[1024];
            int read;
            long totalRead = 0;
            long toRead = metaData.getDataSize();
            int loop = 0;
            if(! SocketHolder.getBluetoothSocket().isConnected()) {
                Log.d(FileReceiverTask.TAG,"Socket is closed... Can't perform file receiving from stream...");
                return null;
            }
            while ((read = inputStream.read(buffer)) != -1) {

                totalRead = totalRead + read;
                outputStreamWriteToFile.write(buffer,0,read);
                loop++;
                //Log.d(FileReceiverTask.TAG,"loop iterations : " + loop + " bytes read: " + totalRead);
                if(totalRead % 1024 == 0) {
                    taskUpdate.TaskProgressPublish(metaData.getFname() + String.valueOf((float)totalRead/toRead*100) + "%");
                }

                //This the most important part...
                if(totalRead == metaData.getDataSize()) {
                    Log.d(FileReceiverTask.TAG,"breaking from loop");
                    break;
                }
            }

            Log.d(FileReceiverTask.TAG,"loop iterations : " + loop + " bytes read: " + totalRead);
            Log.d(FileReceiverTask.TAG,"outputStreamWriteToFile closing");
            outputStreamWriteToFile.close();
            Log.d(FileReceiverTask.TAG,"outputStreamWriteToFile closed");

        } catch (IOException e) {
            e.printStackTrace();
            Log.d(FileReceiverTask.TAG,e.toString() );
            taskUpdate.TaskError(e.toString());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            Log.d(FileReceiverTask.TAG,e.toString() );
            taskUpdate.TaskError(e.toString());
        }

        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        taskUpdate.TaskCompleted(metaData.getFname());
        if(SocketHolder.getBluetoothSocket().isConnected()) {
            Log.d(FileReceiverTask.TAG,"BluetoothSocket is connected");

        } else {
            Log.d(FileReceiverTask.TAG,"BluetoothSocket is ****NOT*** connected");
        }
        Log.d(FileReceiverTask.TAG,"Task execution completed");

    }

    public static File getFileName( String fileName) {
        File dir = new File(Environment.getExternalStorageDirectory(),"Koya");
        try{
            if(dir.mkdir()) {
                System.out.println("Directory created");
            } else {
                System.out.println("Directory is not created");
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return new File(dir.getPath(),fileName);
    }
}

和FileSenderTask.java

   package com.example.bluetoothrecorder.java_codegeeks_approach.utils;

    import android.bluetooth.BluetoothSocket;
    import android.os.AsyncTask;
    import android.util.Log;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;


    public class FileSenderTask extends AsyncTask {

    private static final String TAG = "===FileSenderTask";
    OutputStream outputStream;
    String filePath;
    BluetoothSocket bluetoothSocket;
    TaskUpdate taskUpdate;
    MetaData metaData;
    public FileSenderTask(String path, TaskUpdate taskUpdate) {

    Log.d(FileSenderTask.TAG,"Object created");
    this.taskUpdate = taskUpdate;

    this.bluetoothSocket = SocketHolder.getBluetoothSocket();
    this.filePath = path;
        try {
            this.outputStream = bluetoothSocket.getOutputStream();
            Log.d(FileSenderTask.TAG,"obtained outputStream");

        } catch (IOException e) {
            e.printStackTrace();
            Log.d(FileSenderTask.TAG,"Failed to obtain outputStream");
            Log.d(FileSenderTask.TAG,e.toString());
        }
    }

    @Override
    protected Object doInBackground(Object[] objects) {
        taskUpdate.TaskStarted();
        if(!SocketHolder.getBluetoothSocket().isConnected()) {
            Log.d(FileSenderTask.TAG,"Socket is closed... Can't perform file sending Task...");
            return null;
        }

        //Receive metaData
        try {

            Log.d(FileSenderTask.TAG,"obtain file object for : "+ filePath);
            File file = new File(filePath);

            if(!file.exists()) {
                Log.d(FileSenderTask.TAG,"File does not exist");
                return null ;
            } else {
                Log.d(FileSenderTask.TAG,"File exists");
            }

            ObjectOutputStream objectOutputStream;
            objectOutputStream = new ObjectOutputStream(outputStream);

            metaData = new MetaData(file.length(),file.getName());
            Log.d(FileSenderTask.TAG,"Trying to send : " + metaData.toString());
            objectOutputStream.writeObject(metaData);


            if(!SocketHolder.getBluetoothSocket().isConnected()) {
                Log.d(FileSenderTask.TAG,"Socket is closed... Can't perform file sending on stream...");
                return null;
            }

            Log.d(FileSenderTask.TAG,"fileInputStream open: "+ filePath);
            FileInputStream fileInputStream = new FileInputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            int loop = 0;
            long totalRead = 0;
            long toRead = metaData.getDataSize();
            while ((bytesRead = fileInputStream.read(buffer)) > 0)
            {
                loop++;
                outputStream.write(buffer, 0, bytesRead);
                totalRead = totalRead + bytesRead;
                if(totalRead % 1024 == 0) {
                    taskUpdate.TaskProgressPublish(metaData.getFname() + String.valueOf((float)totalRead/toRead*100) + "%");
                }
            }

            Log.d(FileSenderTask.TAG,"Loop iterations run : " + loop);
            Log.d(FileSenderTask.TAG,"trying to close the fileInputStream...");
            fileInputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
            Log.d(FileSenderTask.TAG,e.toString());
            taskUpdate.TaskError(e.toString());
        } catch (Exception e) {
            taskUpdate.TaskError(e.toString());
        }

        return null;
    }


    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        taskUpdate.TaskCompleted(metaData.getFname());

        if(SocketHolder.getBluetoothSocket().isConnected()) {
            Log.d(FileSenderTask.TAG,"BluetoothSocket is connected");

        } else {
            Log.d(FileSenderTask.TAG,"BluetoothSocket is ****NOT*** connected");
        }

        Log.d(FileSenderTask.TAG,"Task execution completed");

    }
}

谢谢。

0 个答案:

没有答案