Android 端代码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;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.util.Set;import java.util.UUID;public class MainActivity extends AppCompatActivity {private BluetoothAdapter mBluetoothAdapter;//要连接的目标蓝牙设备(Windows PC电脑的名字)。自己更改private final String TARGET_DEVICE_NAME = "*********";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 {Log.d(TAG, "读取"+c);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");String folderName = Environment.getExternalStorageDirectory().getPath() + "/beidou".toString();File saveFile =new File(folderName,"0360405"+".txt".toString());return saveFile;}/*** 获得和当前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);}}
PC端 C#代码
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using ;
using .Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ;
using .Bluetooth;
using .Sockets;
using InTheHand.Windows.Forms;
namespace BD_BLU
{
public partial class Form1 : Form
{
BluetoothRadio radio = null;//蓝牙适配器
string sendFileName = null;//发送文件名
BluetoothAddress sendAddress = null;//发送目的地址
ObexListener listener = null;//监听器
string recDir = null;//接受文件存放目录
Thread listenThread, sendThread, deal_a;//发送/接收线程/处理数据
private NetworkStream peerStream;
bool isconected = true;
BluetoothClient bluetoothClient;
BluetoothListener bluetoothListener;
int yy;
// EventHandler<BluetoothWin32AuthenticationEventArgs> handler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(this.handleRequests);
public Form1()
{
InitializeComponent();
radio = BluetoothRadio.PrimaryRadio;//获取当前PC的蓝牙适配器
CheckForIllegalCrossThreadCalls = false;//不检查跨线程调用
if (radio == null)//检查该电脑蓝牙是否可用
{
MessageBox.Show("这个电脑蓝牙不可用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
recDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
labelRecDir.Text = recDir;
}
private void button2_Click(object sender, EventArgs e)//选择远程蓝牙设备
{
SelectBluetoothDeviceDialog dialog = new SelectBluetoothDeviceDialog();
dialog.ShowRemembered = true;//显示已经记住的蓝牙设备
dialog.ShowAuthenticated = true;//显示认证过的蓝牙设备
dialog.ShowUnknown = true;//显示位置蓝牙设备
if (dialog.ShowDialog() == DialogResult.OK)
{
sendAddress = dialog.SelectedDevice.DeviceAddress;//获取选择的远程蓝牙地址
labelAddress.Text = "地址:" + sendAddress.ToString() + " 设备名:" + dialog.SelectedDevice.DeviceName;
}
}
private void button1_Click(object sender, EventArgs e)//选择要发送的本地文件
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
sendFileName = dialog.FileName;//设置文件名
labelPath.Text = Path.GetFileName(sendFileName);
}
}
private void button3_Click(object sender, EventArgs e)//发送按钮
{
sendThread = new Thread(sendFile);//开启发送文件线程
sendThread.Start();
}
private void sendFile()//发送文件方法
{
ObexWebRequest request = new ObexWebRequest(sendAddress, Path.GetFileName(sendFileName));//创建网络请求
WebResponse response = null;
try
{
buttonSend.Enabled = false;
request.ReadFile(sendFileName);//发送文件
labelInfo.Text = "开始发送!";
response = request.GetResponse();//获取回应
labelInfo.Text = "发送完成!";
}
catch (System.Exception ex)
{
MessageBox.Show("发送失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
labelInfo.Text = "发送失败!";
}
finally
{
if (response != null)
{
response.Close();
buttonSend.Enabled = true;
}
}
}
private void button3_Click_1(object sender, EventArgs e)//选择接受目录
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择蓝牙接收文件的存放路径";
if (dialog.ShowDialog() == DialogResult.OK)
{
recDir = dialog.SelectedPath;
labelRecDir.Text = recDir;
}
}
bool Istrue = true;
private void button4_Click(object sender, EventArgs e)//开始/停止监听
{
if(Istrue)
{
listenThread = new Thread(receiveFile);//开启监听线程
listenThread.Start();
Istrue = false;
}
else
{
listenThread.Abort();
Istrue = true;
}
}
// BluetoothWin32Authentication authenticator = new BluetoothWin32Authentication(handler);
public void handleRequests(Object thing, BluetoothWin32AuthenticationEventArgs args)
{
args.Confirm = true;
}
public static Array Redim(Array origArray, int desiredSize)
{
//determine the type of element
Type t = origArray.GetType().GetElementType();
//create a number of elements with a new array of expectations
//new array type must match the type of the original array
Array newArray = Array.CreateInstance(t, desiredSize);
//copy the original elements of the array to the new array
Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, desiredSize));
//return new array
return newArray;
}
//接收文件 这步最关键
static int i = 0;
public void receiveFile()
{
try
{
Guid mGUID = Guid.Parse("0000110100001000800000805F9B34FB");
bluetoothListener = new BluetoothListener(mGUID);
bluetoothListener.Start();
bluetoothClient = bluetoothListener.AcceptBluetoothClient();
isconected = true;
}
catch (Exception ex)
{
// isconected = false;
}
peerStream = bluetoothClient.GetStream();
// FileStream a = new FileStream("C:/Users/Administrator/Desktop/22.txt", FileMode.Create);
byte[] buffer = new byte[1];
byte[] buffer1 = new byte[4000];
while (isconected)
{
if (peerStream.Read(buffer, 0, 1) > 0)
{
if (bluetoothClient != null && bluetoothClient.Connected)
{
textBox2.Text = Encoding.UTF8.GetString(buffer).ToString();
buffer1[i] = buffer[0];
i++;
}
// textBox1.Text =i.ToString();
yy = i;
}
else
{
textBox1.Text = yy.ToString();
buffer1 = (byte[])Redim(buffer1, yy);
string strPath = "C:/Users/Administrator/Desktop/22.txt";
string value = Encoding.UTF8.GetString(buffer1).ToString();
if (!Directory.Exists(Path.GetDirectoryName(strPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(strPath));
}
File.WriteAllText(strPath, value, Encoding.Default);
i = 0;
}
}
}
//private void receiveFile()//收文件方法
//{
// ObexListenerContext context = null;
// ObexListenerRequest request = null;
// while (listener.IsListening)
// {
// context = listener.GetContext();//获取监听上下文
// if (context == null)
// {
//break;
// }
// request = context.Request;//获取请求
// string uriString = Uri.UnescapeDataString(request.RawUrl);//将uri转换成字符串
// string recFileName = recDir + uriString;
// request.WriteFile(recFileName);//接收文件
// labelRecInfo.Text = "收到文件" + uriString.TrimStart(new char[] { '/' });
// }
//}
private void button6_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "GPX Files (*.txt)|*.txt";
openFileDialog1.CheckFileExists = true;
openFileDialog1.FileName = String.Empty;
openFileDialog1.Multiselect = false;
if (openFileDialog1.ShowDialog() != DialogResult.OK)
return;
OpenGPXFile(openFileDialog1.FileName);
}
private void OpenGPXFile(string Filename)
{
GPX gpx = new GPX(Filename);
ShowGPX(gpx);
dataGridViewGPX.Tag = gpx;
textBox1.Text = gpx.Name;
//textBoxDate.Text = DateTime.Parse(gpx.Time).ToLocalTime().ToString();
//textBox1.Text = double.Parse(trkpt.Attribute("lat").Value).ToString();
// textBox2.Text = gpx.Time;
//splitContainer1.Visible = true;
//buttonAnalyze_Click(null, null);
}
private void ShowGPX(GPX gpx)
{
dataGridViewGPX.DataSource = null;
Application.DoEvents();
DataTable dt = TrackPoint.GetDatatable();
foreach (TrackPoint trackPoint in gpx.TrackPoints)
{
dt.Rows.Add(trackPoint.GetDataRow(dt));
}
dataGridViewGPX.DataSource = dt;
AdjustColumns(dataGridViewGPX.Columns);
}
private void button5_Click(object sender, EventArgs e)
{
textBox1.Text = dataGridViewGPX.Rows[0].Cells[0].Value.ToString();
}
private void AdjustColumns(DataGridViewColumnCollection dataGridViewColumnCollection)
{
dataGridViewColumnCollection["Lat"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewColumnCollection["Lon"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewColumnCollection["Time"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewColumnCollection["Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (sendThread != null)
{
sendThread.Abort();
}
if (listenThread != null)
{
listenThread.Abort();
}
if (listener != null && listener.IsListening)
{
listener.Stop();
}
}
}
如果觉得《Android通过Bluetooth蓝牙发送手机照片文件到电脑Windows PC端》对你有帮助,请点赞、收藏,并留下你的观点哦!