You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过蓝牙从安卓手机向电脑传输多张图片?

Alright, let's fix up your 32feet.net OBEX code to handle multiple image transfers from Android to your PC. Here's what you need to know and the revised implementation:

Key Background on OBEX Multi-File Transfers

When you send multiple images from an Android device over Bluetooth, it typically sends them as multiple PUT requests within the same OBEX connection session. Your original code only handles a single request per connection context, which is why it misses subsequent images. We need to adjust the logic to process all requests from a single connection before moving to the next one.

Revised Code with Multi-Image Support

using System;
using System.IO;
using System.Linq;
using InTheHand.Net.Obex;

// Initialize and start the Bluetooth OBEX listener
ObexListener mBtListener = new ObexListener(ObexTransport.Bluetooth);
mBtListener.Start();

string mUploadFolder = @"C:\BluetoothImageUploads"; // Update this to your target folder
Directory.CreateDirectory(mUploadFolder); // Ensure the folder exists to avoid IO errors

Console.WriteLine("OBEX Bluetooth listener started. Waiting for Android connections...");

try
{
    while (mBtListener.IsListening)
    {
        // Get the connection context (one per Android device connection)
        ObexListenerContext obexContext = mBtListener.GetContext();
        if (obexContext == null) continue;

        Console.WriteLine($"New connection from device: {obexContext.RemoteEndPoint}");

        try
        {
            // Process ALL requests from this connection (handles multiple images in one session)
            while (true)
            {
                ObexListenerRequest req = obexContext.GetRequest();
                if (req == null) break; // No more requests in this session

                try
                {
                    // Extract the original filename from OBEX headers
                    if (!req.Headers.Contains(ObexHeaderName.Name))
                    {
                        Console.WriteLine("Skipping request: No filename provided");
                        req.StatusCode = ObexStatusCode.BadRequest;
                        req.Close();
                        continue;
                    }

                    string originalFileName = req.Headers[ObexHeaderName.Name].ToString();
                    string savePath = Path.Combine(mUploadFolder, originalFileName);

                    // Avoid overwriting existing files by adding a counter suffix
                    int fileCounter = 1;
                    while (File.Exists(savePath))
                    {
                        string baseName = Path.GetFileNameWithoutExtension(originalFileName);
                        string extension = Path.GetExtension(originalFileName);
                        savePath = Path.Combine(mUploadFolder, $"{baseName}_{fileCounter}{extension}");
                        fileCounter++;
                    }

                    // Only save valid image files
                    if (IsImage(originalFileName))
                    {
                        req.WriteFile(savePath);
                        Console.WriteLine($"✅ Saved image: {savePath}");
                        req.StatusCode = ObexStatusCode.Success;
                    }
                    else
                    {
                        Console.WriteLine($"❌ Skipping non-image file: {originalFileName}");
                        req.StatusCode = ObexStatusCode.NotAcceptable;
                    }

                    req.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"⚠️ Error processing request: {ex.Message}");
                    req?.Close();
                }
            }
        }
        finally
        {
            obexContext.Close();
            Console.WriteLine("🔌 Connection closed");
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine($"❌ Listener failure: {ex.Message}");
}
finally
{
    mBtListener.Stop();
    Console.WriteLine("Listener stopped");
}

// Helper method to validate image file extensions
private bool IsImage(string fileName)
{
    string[] validImageExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
    string fileExtension = Path.GetExtension(fileName).ToLowerInvariant();
    return validImageExtensions.Contains(fileExtension);
}

Critical Changes Explained

  • Nested Request Loop: After getting a connection context, we add an inner while(true) loop to call GetRequest() repeatedly. This captures all images sent in the same OBEX session from Android.
  • Filename Deduplication: Added logic to avoid overwriting existing files by appending a counter to duplicate filenames.
  • Robust Error Handling: Wrapped request processing in try/catch blocks so a single failed transfer doesn't take down the entire listener.
  • Explicit Status Codes: Return clear OBEX status codes to the Android device (success, bad request, not acceptable) so it knows how the transfer went.
  • Folder Initialization: Ensured the upload folder exists before saving files to avoid unexpected IO errors.

Additional Notes

  • Make sure your PC's Bluetooth is discoverable and paired with the Android device.
  • Android's default share menu uses OBEX for Bluetooth file transfers, so selecting multiple images and sharing via Bluetooth should work seamlessly with this code.
  • Keep your 32feet.net NuGet package updated to the latest stable version to avoid known OBEX session bugs.

内容的提问来源于stack exchange,提问作者Явор Налбантов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:23:18