Android通過Bluetooth藍牙發送手機照片文件到Windows PC:Java實現
本文在《Android通過藍牙發送數據到Windows PC電腦:Java實現(鏈接地址:https://blog.csdn.net/zhangphil/article/details/83146705 )》基礎上改進代碼,還是用Java實現把Android手機上的一張照片,通過Bluetooth藍牙連接,發送到Windows PC電腦上,實現上仍區分為Windows電腦端的藍牙服務器端BluetoothJavaServer:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;/*** BluetoothJavaServer是藍牙的服務器端。部署在Windows操作系統(PC電腦上)。 等待手機客戶端或者其他藍牙設備的連接。* * @author fly**/
public class BluetoothJavaServer {// 藍牙服務器端的UUID必須和手機端的UUID一致。// 手機端的UUID需要去掉中間的-分割符。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("服務器端開始監聽客戶端連接請求...");while (true) {StreamConnection connection = mStreamConnectionNotifier.acceptAndOpen();System.out.println("接受客戶端連接");new ClientThread(connection).start();}} catch (Exception e) {e.printStackTrace();}}/*** 開啟一個線程專門從與客戶端藍牙設備中讀取文件數據,并把文件數據存儲到本地。* * @author fly**/private class ClientThread extends Thread {private StreamConnection mStreamConnection = null;public ClientThread(StreamConnection sc) {mStreamConnection = sc;}@Overridepublic void run() {try {BufferedInputStream bis = new BufferedInputStream(mStreamConnection.openInputStream());// 本地創建一個image.jpg文件接收來自于手機客戶端發來的圖片文件數據。FileOutputStream fos = new FileOutputStream("image.jpg");int c = 0;byte[] buffer = new byte[1024];System.out.println("開始讀數據...");while (true) {c = bis.read(buffer);if (c == -1) {System.out.println("讀取數據結束");break;} else {fos.write(buffer, 0, c);}}fos.flush();fos.close();bis.close();mStreamConnection.close();} catch (Exception e) {e.printStackTrace();}}}
}
Android手機端的藍牙客戶端BluetoothClientActivity:
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;//要連接的目標藍牙設備(Windows PC電腦的名字)。private final String TARGET_DEVICE_NAME = "PHIL-PC";private final String TAG = "藍牙調試";//UUID必須是Android藍牙客戶端和Windows PC電腦端一致。private final String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";// 通過廣播接收系統發送出來的藍牙設備發現通知。private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {@Overridepublic 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, "發現藍牙設備:" + name);if (name != null && name.equals("PHIL-PC")) {Log.d(TAG, "發現目標藍牙設備,開始線程連接");new Thread(new ClientThread(device)).start();// 藍牙搜索是非常消耗系統資源開銷的過程,一旦發現了目標感興趣的設備,可以關閉掃描。mBluetoothAdapter.cancelDiscovery();}}}};/*** 該線程往藍牙服務器端發送文件數據。*/private class ClientThread extends Thread {private BluetoothDevice device;public ClientThread(BluetoothDevice device) {this.device = device;}@Overridepublic void run() {BluetoothSocket socket;try {socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));Log.d(TAG, "連接藍牙服務端...");socket.connect();Log.d(TAG, "連接建立.");// 開始往服務器端發送數據。Log.d(TAG, "開始往藍牙服務器發送數據...");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, "讀取結束");break;} else {bos.write(buffer, 0, c);}}bos.flush();fis.close();bos.close();Log.d(TAG, "發送文件成功");} catch (Exception e) {e.printStackTrace();}}}/*** 發給給藍牙服務器的文件。* 本例發送一張位于存儲器根目錄下名為 image.jpg 的照片。** @return*/private File getFile() {File root = Environment.getExternalStorageDirectory();File file = new File(root, "image.jpg");return file;}/*** 獲得和當前Android藍牙已經配對的藍牙設備。** @return*/private BluetoothDevice getPairedDevices() {Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();if (pairedDevices != null && pairedDevices.size() > 0) {for (BluetoothDevice device : pairedDevices) {// 把已經取得配對的藍牙設備名字和地址打印出來。Log.d(TAG, device.getName() + " : " + device.getAddress());//如果已經發現目標藍牙設備和Android藍牙已經配對,則直接返回。if (TextUtils.equals(TARGET_DEVICE_NAME, device.getName())) {Log.d(TAG, "已配對目標設備 -> " + TARGET_DEVICE_NAME);return device;}}}return null;}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();BluetoothDevice device = getPairedDevices();if (device == null) {// 注冊廣播接收器。// 接收系統發送的藍牙發現通知事件。IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(mBroadcastReceiver, filter);if (mBluetoothAdapter.startDiscovery()) {Log.d(TAG, "搜索藍牙設備...");}} else {new ClientThread(device).start();}}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(mBroadcastReceiver);}
}
本例出于簡單演示功能的目的,省去了Android客戶端選擇文件的代碼實現,事先作為測試文件,先在Android手機的存儲器根目錄放置一張名為image.jpg的圖片。
務必保證Windows電腦和Android手機上的藍牙均處于打開狀態。然后先啟動服務器端程序,再啟動Android手機客戶端程序。
Windows電腦端輸出:
Android studio的logcat輸出:
總結
以上是生活随笔為你收集整理的Android通过Bluetooth蓝牙发送手机照片文件到Windows PC:Java实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。