Android sends mobile photo files to Windows PC via Bluetooth: Java implementation

Keywords: Mobile Android Java Windows

This paper improves the code on the basis of "Android sends data to Windows PC through Bluetooth: Java implementation" (link address: https://blog.csdn.net/zhangphil/article/details/83146705). Or does it use Java implementation to send a picture on Android mobile phone to Windows PC through Bluetooth connection and realize Bluetooth service which is still distinguished from Windows PC side? Bluetooth Java Server on the server side:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

/**
 * BluetoothJavaServer It's the server side of Bluetooth. Deployed on Windows Operating System (PC). Wait for the connection of the mobile client or other Bluetooth devices.
 * 
 * @author fly
 *
 */
public class BluetoothJavaServer {
	// The UUID on the Bluetooth server side must be consistent with the UUID on the mobile phone side.
	// UUID s on the phone end need to remove the middle - separator.
	private String MY_UUID = "0000110100001000800000805F9B34FB";

	public static void main(String[] args) {
		new BluetoothJavaServer();
	}

	public BluetoothJavaServer() {
		StreamConnectionNotifier mStreamConnectionNotifier = null;

		try {
			mStreamConnectionNotifier = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + MY_UUID);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			System.out.println("Server begins to listen for client connection requests...");
			while (true) {
				StreamConnection connection = mStreamConnectionNotifier.acceptAndOpen();
				System.out.println("Accept client connection");

				new ClientThread(connection).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open a thread to read file data from Bluetooth devices with the client and store the file data locally.
	 * 
	 * @author fly
	 *
	 */
	private class ClientThread extends Thread {
		private StreamConnection mStreamConnection = null;

		public ClientThread(StreamConnection sc) {
			mStreamConnection = sc;
		}

		@Override
		public void run() {
			try {
				BufferedInputStream bis = new BufferedInputStream(mStreamConnection.openInputStream());

				// Create an image.jpg file locally to receive the image file data from the mobile client.
				FileOutputStream fos = new FileOutputStream("image.jpg");

				int c = 0;
				byte[] buffer = new byte[1024];

				System.out.println("Start reading data...");
				while (true) {
					c = bis.read(buffer);
					if (c == -1) {
						System.out.println("End of reading data");
						break;
					} else {
						fos.write(buffer, 0, c);
					}
				}

				fos.flush();

				fos.close();
				bis.close();
				mStreamConnection.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}


Bluetooth Client Activity on Android Mobile:

package zhangphil.test;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Set;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;

public class BluetoothClientActivity extends AppCompatActivity {
    private BluetoothAdapter mBluetoothAdapter;

    //The target Bluetooth device to connect to (the name of a Windows PC computer).
    private final String TARGET_DEVICE_NAME = "PHIL-PC";

    private final String TAG = "Bluetooth debugging";

    //UUID must be the same as Android Bluetooth client and Windows PC client.
    private final String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";

    // Bluetooth device discovery notification sent by broadcast receiving system.
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                String name = device.getName();
                if (name != null)
                    Log.d(TAG, "Discovery of Bluetooth Devices:" + name);

                if (name != null && name.equals("PHIL-PC")) {
                    Log.d(TAG, "Discover the target Bluetooth device and start thread connection");
                    new Thread(new ClientThread(device)).start();

                    // Bluetooth search is a process that consumes a lot of system resources. Once the target device is found, the scan can be turned off.
                    mBluetoothAdapter.cancelDiscovery();
                }
            }
        }
    };

    /**
     * The thread sends file data to the Bluetooth server.
     */
    private class ClientThread extends Thread {
        private BluetoothDevice device;

        public ClientThread(BluetoothDevice device) {
            this.device = device;
        }

        @Override
        public void run() {
            BluetoothSocket socket;

            try {
                socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));

                Log.d(TAG, "Connect Bluetooth Server...");
                socket.connect();
                Log.d(TAG, "Connection establishment.");

                // Start sending data to the server.
                Log.d(TAG, "Start sending data to Bluetooth server...");
                sendDataToServer(socket);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void sendDataToServer(BluetoothSocket socket) {
            try {
                FileInputStream fis = new FileInputStream(getFile());
                BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

                byte[] buffer = new byte[1024];
                int c;
                while (true) {
                    c = fis.read(buffer);
                    if (c == -1) {
                        Log.d(TAG, "End of reading");
                        break;
                    } else {
                        bos.write(buffer, 0, c);
                    }
                }

                bos.flush();

                fis.close();
                bos.close();

                Log.d(TAG, "Successful sending of files");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Files sent to Bluetooth servers.
     * This example sends a picture named image.jpg in the memory root directory.
     *
     * @return
     */
    private File getFile() {
        File root = Environment.getExternalStorageDirectory();
        File file = new File(root, "image.jpg");
        return file;
    }

    /**
     * Get the Bluetooth device that has been paired with the current Android Bluetooth.
     *
     * @return
     */
    private BluetoothDevice getPairedDevices() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices != null && pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                // Print out the name and address of the Bluetooth device that has been paired.
                Log.d(TAG, device.getName() + " : " + device.getAddress());

                //If the target Bluetooth device and Android Bluetooth have been found to be paired, return directly.
                if (TextUtils.equals(TARGET_DEVICE_NAME, device.getName())) {
                    Log.d(TAG, "Matched target equipment -> " + TARGET_DEVICE_NAME);
                    return device;
                }
            }
        }

        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = getPairedDevices();
        if (device == null) {
            // Register the broadcast receiver.
            // Bluetooth Discovery Notification Event sent by Receiving System.
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver, filter);

            if (mBluetoothAdapter.startDiscovery()) {
                Log.d(TAG, "Search for Bluetooth Devices...");
            }
        } else {
            new ClientThread(device).start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }
}


For the purpose of simple demonstration function, the code implementation of Android client selection file is omitted. As a test file in advance, an image named image.jpg is placed in the memory root directory of Android mobile phone.
Make sure that Bluetooth on both Windows computers and Android phones is on. Then start the server-side program, and then start the Android mobile client program.
Windows computer output:


Android studio logcat output:

Posted by Donovan on Tue, 29 Jan 2019 20:03:14 -0800