انتقال داده های بلوتوث
با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
بعد از اینکه با موفقیت به یک دستگاه بلوتوث متصل شدید، هر کدام یک BluetoothSocket
متصل دارند. اکنون می توانید اطلاعات را بین دستگاه ها به اشتراک بگذارید. با استفاده از BluetoothSocket
، روش کلی برای انتقال داده ها به شرح زیر است:
InputStream
و OutputStream
را دریافت کنید که به ترتیب با استفاده از getInputStream()
و getOutputStream()
انتقال را از طریق سوکت انجام می دهند.
خواندن و نوشتن داده ها در جریان ها با استفاده از read(byte[])
و write(byte[])
.
البته جزئیات اجرایی وجود دارد که باید در نظر گرفته شود. به ویژه، شما باید از یک موضوع اختصاصی برای خواندن از جریان و نوشتن روی آن استفاده کنید. این مهم است زیرا هر دو روش read(byte[])
و write(byte[])
تماس ها را مسدود می کنند. متد read(byte[])
مسدود میشود تا زمانی که چیزی برای خواندن از جریان وجود داشته باشد. روش write(byte[])
معمولاً مسدود نمی شود، اما اگر دستگاه راه دور به اندازه کافی سریع read(byte[])
صدا نزند و در نتیجه بافرهای میانی پر شوند، می تواند برای کنترل جریان مسدود شود. بنابراین، باید حلقه اصلی خود را در موضوع به خواندن از InputStream
اختصاص دهید. می توانید از یک روش عمومی جداگانه در رشته برای شروع نوشتن در OutputStream
استفاده کنید.
مثال
در زیر مثالی از نحوه انتقال داده بین دو دستگاه متصل از طریق بلوتوث ارائه شده است:
کاتلین
private const val TAG = "MY_APP_DEBUG_TAG"
// Defines several constants used when transmitting messages between the
// service and the UI.
const val MESSAGE_READ: Int = 0
const val MESSAGE_WRITE: Int = 1
const val MESSAGE_TOAST: Int = 2
// ... (Add other message types here as needed.)
class MyBluetoothService(
// handler that gets info from Bluetooth service
private val handler: Handler) {
private inner class ConnectedThread(private val mmSocket: BluetoothSocket) : Thread() {
private val mmInStream: InputStream = mmSocket.inputStream
private val mmOutStream: OutputStream = mmSocket.outputStream
private val mmBuffer: ByteArray = ByteArray(1024) // mmBuffer store for the stream
override fun run() {
var numBytes: Int // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
// Read from the InputStream.
numBytes = try {
mmInStream.read(mmBuffer)
} catch (e: IOException) {
Log.d(TAG, "Input stream was disconnected", e)
break
}
// Send the obtained bytes to the UI activity.
val readMsg = handler.obtainMessage(
MESSAGE_READ, numBytes, -1,
mmBuffer)
readMsg.sendToTarget()
}
}
// Call this from the main activity to send data to the remote device.
fun write(bytes: ByteArray) {
try {
mmOutStream.write(bytes)
} catch (e: IOException) {
Log.e(TAG, "Error occurred when sending data", e)
// Send a failure message back to the activity.
val writeErrorMsg = handler.obtainMessage(MESSAGE_TOAST)
val bundle = Bundle().apply {
putString("toast", "Couldn't send data to the other device")
}
writeErrorMsg.data = bundle
handler.sendMessage(writeErrorMsg)
return
}
// Share the sent message with the UI activity.
val writtenMsg = handler.obtainMessage(
MESSAGE_WRITE, -1, -1, mmBuffer)
writtenMsg.sendToTarget()
}
// Call this method from the main activity to shut down the connection.
fun cancel() {
try {
mmSocket.close()
} catch (e: IOException) {
Log.e(TAG, "Could not close the connect socket", e)
}
}
}
}
جاوا
public class MyBluetoothService {
private static final String TAG = "MY_APP_DEBUG_TAG";
private Handler handler; // handler that gets info from Bluetooth service
// Defines several constants used when transmitting messages between the
// service and the UI.
private interface MessageConstants {
public static final int MESSAGE_READ = 0;
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_TOAST = 2;
// ... (Add other message types here as needed.)
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer; // mmBuffer store for the stream
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams; using temp objects because
// member streams are final.
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = handler.obtainMessage(
MessageConstants.MESSAGE_READ, numBytes, -1,
mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
Log.d(TAG, "Input stream was disconnected", e);
break;
}
}
}
// Call this from the main activity to send data to the remote device.
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
// Share the sent message with the UI activity.
Message writtenMsg = handler.obtainMessage(
MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
writtenMsg.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
// Send a failure message back to the activity.
Message writeErrorMsg =
handler.obtainMessage(MessageConstants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString("toast",
"Couldn't send data to the other device");
writeErrorMsg.setData(bundle);
handler.sendMessage(writeErrorMsg);
}
}
// Call this method from the main activity to shut down the connection.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
}
پس از اینکه سازنده جریان های لازم را به دست آورد، رشته منتظر می ماند تا داده ها از طریق InputStream
بیایند. وقتی read(byte[])
با دادههای جریان برمیگردد، دادهها با استفاده از یک عضو Handler
از کلاس والد به فعالیت اصلی ارسال میشوند. سپس رشته منتظر می ماند تا بایت های بیشتری از InputStream
خوانده شود.
برای ارسال دادههای خروجی، متد write()
رشته را از اکتیویتی اصلی فراخوانی میکنید و بایتهای ارسالی را ارسال میکنید. این روش write(byte[])
برای ارسال داده ها به دستگاه راه دور فراخوانی می کند. اگر هنگام فراخوانی write(byte[])
یک IOException
پرتاب شود، رشته یک نان تست برای فعالیت اصلی ارسال می کند و به کاربر توضیح می دهد که دستگاه نمی تواند بایت های داده شده را به دستگاه دیگر (متصل) ارسال کند.
متد cancel()
thread به شما این امکان را میدهد که اتصال را در هر زمان با بستن BluetoothSocket
قطع کنید. وقتی کارتان با اتصال بلوتوث تمام شد، همیشه با این روش تماس بگیرید.
برای نمایش استفاده از APIهای بلوتوث، به برنامه نمونه گپ بلوتوث در GitHub مراجعه کنید.
محتوا و نمونه کدها در این صفحه مشمول پروانههای توصیفشده در پروانه محتوا هستند. جاوا و OpenJDK علامتهای تجاری یا علامتهای تجاری ثبتشده Oracle و/یا وابستههای آن هستند.
تاریخ آخرین بهروزرسانی 2025-07-29 بهوقت ساعت هماهنگ جهانی.
[null,null,["تاریخ آخرین بهروزرسانی 2025-07-29 بهوقت ساعت هماهنگ جهانی."],[],[],null,["# Transfer Bluetooth data\n\nAfter you have successfully [connected to a Bluetooth\ndevice](/develop/connectivity/bluetooth/connect-bluetooth-devices), each\none has a connected\n[`BluetoothSocket`](/reference/android/bluetooth/BluetoothSocket). You can now\nshare information between devices. Using the `BluetoothSocket`, the general\nprocedure to transfer data is as follows:\n\n1. Get the [`InputStream`](/reference/java/io/InputStream) and\n [`OutputStream`](/reference/java/io/OutputStream) that handle transmissions\n through the socket using\n [`getInputStream()`](/reference/android/bluetooth/BluetoothSocket#getInputStream())\n and\n [`getOutputStream()`](/reference/android/bluetooth/BluetoothSocket#getOutputStream()),\n respectively.\n\n2. Read and write data to the streams using\n [`read(byte[])`](/reference/java/io/InputStream#read(byte%5B%5D)) and\n [`write(byte[])`](/reference/java/io/OutputStream#write(byte%5B%5D)).\n\nThere are, of course, implementation details to consider. In particular, you\nshould use a dedicated thread for reading from the stream and writing to it.\nThis is important because both the `read(byte[])` and `write(byte[])` methods\nare blocking calls. The `read(byte[])` method blocks until there is something to\nread from the stream. The `write(byte[])` method doesn't usually block, but it\ncan block for flow control if the remote device isn't calling `read(byte[])`\nquickly enough and the intermediate buffers become full as a result. So, you\nshould dedicate your main loop in the thread to reading from the `InputStream`.\nYou can use a separate public method in the thread to initiate writes to the\n`OutputStream`.\n\nExample\n-------\n\nThe following is an example of how you can transfer data between two devices\nconnected over Bluetooth: \n\n### Kotlin\n\n```kotlin\nprivate const val TAG = \"MY_APP_DEBUG_TAG\"\n\n// Defines several constants used when transmitting messages between the\n// service and the UI.\nconst val MESSAGE_READ: Int = 0\nconst val MESSAGE_WRITE: Int = 1\nconst val MESSAGE_TOAST: Int = 2\n// ... (Add other message types here as needed.)\n\nclass MyBluetoothService(\n // handler that gets info from Bluetooth service\n private val handler: Handler) {\n\n private inner class ConnectedThread(private val mmSocket: BluetoothSocket) : Thread() {\n\n private val mmInStream: InputStream = mmSocket.inputStream\n private val mmOutStream: OutputStream = mmSocket.outputStream\n private val mmBuffer: ByteArray = ByteArray(1024) // mmBuffer store for the stream\n\n override fun run() {\n var numBytes: Int // bytes returned from read()\n\n // Keep listening to the InputStream until an exception occurs.\n while (true) {\n // Read from the InputStream.\n numBytes = try {\n mmInStream.read(mmBuffer)\n } catch (e: IOException) {\n Log.d(TAG, \"Input stream was disconnected\", e)\n break\n }\n\n // Send the obtained bytes to the UI activity.\n val readMsg = handler.obtainMessage(\n MESSAGE_READ, numBytes, -1,\n mmBuffer)\n readMsg.sendToTarget()\n }\n }\n\n // Call this from the main activity to send data to the remote device.\n fun write(bytes: ByteArray) {\n try {\n mmOutStream.write(bytes)\n } catch (e: IOException) {\n Log.e(TAG, \"Error occurred when sending data\", e)\n\n // Send a failure message back to the activity.\n val writeErrorMsg = handler.obtainMessage(MESSAGE_TOAST)\n val bundle = Bundle().apply {\n putString(\"toast\", \"Couldn't send data to the other device\")\n }\n writeErrorMsg.data = bundle\n handler.sendMessage(writeErrorMsg)\n return\n }\n\n // Share the sent message with the UI activity.\n val writtenMsg = handler.obtainMessage(\n MESSAGE_WRITE, -1, -1, mmBuffer)\n writtenMsg.sendToTarget()\n }\n\n // Call this method from the main activity to shut down the connection.\n fun cancel() {\n try {\n mmSocket.close()\n } catch (e: IOException) {\n Log.e(TAG, \"Could not close the connect socket\", e)\n }\n }\n }\n}\n```\n\n### Java\n\n```java\npublic class MyBluetoothService {\n private static final String TAG = \"MY_APP_DEBUG_TAG\";\n private Handler handler; // handler that gets info from Bluetooth service\n\n // Defines several constants used when transmitting messages between the\n // service and the UI.\n private interface MessageConstants {\n public static final int MESSAGE_READ = 0;\n public static final int MESSAGE_WRITE = 1;\n public static final int MESSAGE_TOAST = 2;\n\n // ... (Add other message types here as needed.)\n }\n\n private class ConnectedThread extends Thread {\n private final BluetoothSocket mmSocket;\n private final InputStream mmInStream;\n private final OutputStream mmOutStream;\n private byte[] mmBuffer; // mmBuffer store for the stream\n\n public ConnectedThread(BluetoothSocket socket) {\n mmSocket = socket;\n InputStream tmpIn = null;\n OutputStream tmpOut = null;\n\n // Get the input and output streams; using temp objects because\n // member streams are final.\n try {\n tmpIn = socket.getInputStream();\n } catch (IOException e) {\n Log.e(TAG, \"Error occurred when creating input stream\", e);\n }\n try {\n tmpOut = socket.getOutputStream();\n } catch (IOException e) {\n Log.e(TAG, \"Error occurred when creating output stream\", e);\n }\n\n mmInStream = tmpIn;\n mmOutStream = tmpOut;\n }\n\n public void run() {\n mmBuffer = new byte[1024];\n int numBytes; // bytes returned from read()\n\n // Keep listening to the InputStream until an exception occurs.\n while (true) {\n try {\n // Read from the InputStream.\n numBytes = mmInStream.read(mmBuffer);\n // Send the obtained bytes to the UI activity.\n Message readMsg = handler.obtainMessage(\n MessageConstants.MESSAGE_READ, numBytes, -1,\n mmBuffer);\n readMsg.sendToTarget();\n } catch (IOException e) {\n Log.d(TAG, \"Input stream was disconnected\", e);\n break;\n }\n }\n }\n\n // Call this from the main activity to send data to the remote device.\n public void write(byte[] bytes) {\n try {\n mmOutStream.write(bytes);\n\n // Share the sent message with the UI activity.\n Message writtenMsg = handler.obtainMessage(\n MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);\n writtenMsg.sendToTarget();\n } catch (IOException e) {\n Log.e(TAG, \"Error occurred when sending data\", e);\n\n // Send a failure message back to the activity.\n Message writeErrorMsg =\n handler.obtainMessage(MessageConstants.MESSAGE_TOAST);\n Bundle bundle = new Bundle();\n bundle.putString(\"toast\",\n \"Couldn't send data to the other device\");\n writeErrorMsg.setData(bundle);\n handler.sendMessage(writeErrorMsg);\n }\n }\n\n // Call this method from the main activity to shut down the connection.\n public void cancel() {\n try {\n mmSocket.close();\n } catch (IOException e) {\n Log.e(TAG, \"Could not close the connect socket\", e);\n }\n }\n }\n}\n```\n\nAfter the constructor acquires the necessary streams, the thread waits for data\nto come through the `InputStream`. When `read(byte[])` returns with data from\nthe stream, the data is sent to the main activity using a member\n[`Handler`](/reference/android/os/Handler) from the parent class. The thread\nthen waits for more bytes to be read from the `InputStream`.\n\nTo send outgoing data, you call the thread's `write()` method from the main\nactivity and pass in the bytes to be sent. This method calls `write(byte[])` to\nsend the data to the remote device. If an\n[`IOException`](/reference/java/io/IOException) is thrown when calling\n`write(byte[])`, the thread sends a toast to the main activity, explaining to\nthe user that the device couldn't send the given bytes to the other\n(connected) device.\n\nThe thread's `cancel()` method allows you to terminate the connection at any\ntime by closing the `BluetoothSocket`. Always call this method when you're done\nusing the Bluetooth connection.\n\nFor a demonstration of using the Bluetooth APIs, see the [Bluetooth Chat sample\napp](https://github.com/android/connectivity-samples/tree/master/BluetoothChat)\non GitHub."]]