Android 蓝牙如何读取byte.tounsignedint byte类型的数据

android 蓝牙 inputstream怎么读入30个字节流_百度知道
android 蓝牙 inputstream怎么读入30个字节流
我有更好的答案
。 byte []的缓冲区=新的字节[1024]; 整数READINDEX; 的OutputStream =新的缓冲输出流(响应的getOutputStream()),0.write(缓冲液.length))){ outputStream,0,!同时(-1 =(READINDEX = InputStream中读取(缓冲液,应该不会影响结果。我平时当设置为1024,即1KB 这是我成功的代码的InputStream =新的缓冲输入流(新文件输入流( DownloadFile将))的一部分这应该是刚刚的缓冲区长度而已
byte bytes[]=new bytes[30];instream.read(bytes);
为您推荐:
其他类似问题
inputstream的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。Android蓝牙通信聊天实现发送和接受功能
转载 & & 作者:liudao7994
这篇文章主要为大家详细介绍了Android蓝牙通信聊天实现发送和接受功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
很不错的蓝牙通信demo实现发送和接受功能,就用了两个类就实现了,具体内容如下
说下思路把 主要有两个类 主界面类 和 蓝牙聊天服务类&。 首先创建线程 实际上就是创建BluetoothChatService() (蓝牙聊天服务类) 这个时候把handler 传过去 这样就可以操作UI 界面了,在线程中不断轮询读取蓝牙消息,当主界面点击发送按钮时 调用BluetoothChatService 的发送方法write 方法,这里的write 方法 使用了handler 发送消息,在主界面显示,另一个 客户端 不断读取蓝牙消息 类似的有个read 方法 同样显示到界面上去,这样就完成了通信了。
import java.util.ArrayL
import java.util.S
import android.app.A
import android.app.AlertD
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.content.BroadcastR
import android.content.C
import android.content.DialogI
import android.content.I
import android.content.IntentF
import android.os.B
import android.os.H
import android.os.M
import android.util.L
import android.view.M
import android.view.MenuI
import android.view.V
import android.view.View.OnClickL
import android.view.W
import android.widget.B
import android.widget.EditT
import android.widget.TextV
import android.widget.T
public class BluetoothChat extends Activity {
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private TextView mT
private EditText text_
private EditText text_
private Button but_On_O
private Button but_ // ------& 在菜单中可以搜索
private Button but_ // ------& 在菜单中设置"可被发现"
private Button mSendB
// 连接到的蓝牙设备的名称
private String mConnectedDeviceN
// String buffer for outgoing messages
private StringBuffer mOutStringB
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter =
// Member object for the chat services
private BluetoothChatService mChatService =
private ArrayList&String& mPairedDevicesList = new ArrayList&String&();
private ArrayList&String& mNewDevicesList = new ArrayList&String&();
private String[] strN
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
mTitle = (TextView) this.findViewById(R.id.text_title);
text_chat = (EditText) this.findViewById(R.id.text_chat);
text_input = (EditText) this.findViewById(R.id.text_input);
but_On_Off = (Button) this.findViewById(R.id.but_off_on);
but_search = (Button) this.findViewById(R.id.but_search_div);
but_create = (Button) this.findViewById(R.id.but_cjlj);
mSendButton = (Button) this.findViewById(R.id.but_fsxx);
// 获得本地的蓝牙适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 如果为null,说明没有蓝牙设备
if (mBluetoothAdapter == null) {
Toast.makeText(this, "没有蓝牙设备", Toast.LENGTH_LONG).show();
if (mBluetoothAdapter.isEnabled()) {
but_On_Off.setText("关闭蓝牙");
but_On_Off.setText("开启蓝牙");
but_On_Off.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
Toast.makeText(BluetoothChat.this, "蓝牙已开启",
Toast.LENGTH_SHORT).show();
but_On_Off.setText("关闭蓝牙");
mBluetoothAdapter.disable();
Toast.makeText(BluetoothChat.this, "蓝牙已关闭",
Toast.LENGTH_SHORT).show();
but_On_Off.setText("开启蓝牙");
but_search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
searchDevice();
but_create.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final EditText et = new EditText(BluetoothChat.this);
et.setSingleLine();
et.setText(mBluetoothAdapter.getName());
new AlertDialog.Builder(BluetoothChat.this)
.setTitle("请输入房间名:")
.setView(et)
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
String name = et.getText().toString()
if (name.equals("")) {
Toast.makeText(BluetoothChat.this,
"请输入房间名",
Toast.LENGTH_SHORT).show();
// 设置房间名
mBluetoothAdapter.setName(name);
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}).create().show();
// 创建连接,也就是设备本地蓝牙设备可被其他用户的蓝牙搜到
ensureDiscoverable();
// 获得一个已经配对的蓝牙设备的set集合
Set&BluetoothDevice& pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() & 0) {
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesList.add("已配对:" + device.getName() + "\n"
+ device.getAddress());
Toast.makeText(this, "没有已配对的设备", Toast.LENGTH_SHORT).show();
// 当发现一个新的蓝牙设备时注册广播
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// 当搜索完毕后注册广播
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
if (mChatService == null)
setupChat();
public synchronized void onResume() {
super.onResume();
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity
// returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't
// started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
private void setupChat() {
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
String message = text_input.getText().toString();
sendMessage(message);
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null)
mChatService.stop();
// Make sure we're not doing discovery anymore
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
/** 使本地的蓝牙设备可被发现 */
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
* Sends a message.
* @param message
A string of text to send.
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, "没有连接上", Toast.LENGTH_SHORT).show();
// Check that there's actually something to send
if (message.length() & 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
text_input.setText(mOutStringBuffer);
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mTitle.setText("已经连接");
mTitle.append(mConnectedDeviceName);
// mConversationArrayAdapter.clear();
case BluetoothChatService.STATE_CONNECTING:
mTitle.setText("正在连接中...");
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
mTitle.setText("未连接上");
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.
// construct a string from the buffer
String writeMessage = new String(writeBuf);
// mConversationArrayAdapter.add("Me: " + writeMessage);
text_chat.append("我:" + writeMessage + "\n");
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
// mConversationArrayAdapter.add(mConnectedDeviceName+": " +
// readMessage);
text_chat.append(mConnectedDeviceName + ":" + readMessage
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(),
"连接到 " + mConnectedDeviceName, Toast.LENGTH_SHORT)
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
// 连接蓝牙设备
private void linkDevice() {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
int cou = mPairedDevicesList.size() + mNewDevicesList.size();
if (cou == 0) {
Toast.makeText(BluetoothChat.this, "没有搜索到可用的蓝牙设备",
Toast.LENGTH_SHORT).show();
// 把已经配对的蓝牙设备和新发现的蓝牙设备的名称都放入数组中,以便在对话框列表中显示
strName = new String[cou];
for (int i = 0; i & mPairedDevicesList.size(); i++) {
strName[i] = mPairedDevicesList.get(i);
for (int i = mPairedDevicesList.size(); i & strName. i++) {
strName[i] = mNewDevicesList.get(i - mPairedDevicesList.size());
address = strName[0].substring(strName[0].length() - 17);
new AlertDialog.Builder(BluetoothChat.this)
.setTitle("搜索到的蓝牙设备:")
.setSingleChoiceItems(strName, 0,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// 当用户点击选中的蓝牙设备时,取出选中的蓝牙设备的MAC地址
address = strName[which].split("\\n")[1].trim();
.setPositiveButton("连接", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (address == null) {
Toast.makeText(BluetoothChat.this, "请先连接外部蓝牙设备",
Toast.LENGTH_SHORT).show();
Log.i("sxd", "address:" + address);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device);
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}).create().show();
// 搜索蓝牙设备蓝牙设备
private void searchDevice() {
mTitle.setText("正在努力搜索中...");
setProgressBarIndeterminateVisibility(true);
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
mNewDevicesList.clear();
mBluetoothAdapter.startDiscovery();
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 1, 0, "搜索设备");
menu.add(0, 2, 0, "可被发现");
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// 当发现一个新的蓝牙设备时
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed
// already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
String s = "未配对: " + device.getName() + "\n"
+ device.getAddress();
if (!mNewDevicesList.contains(s))
mNewDevicesList.add(s);
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
setProgressBarIndeterminateVisibility(false);
if (mNewDevicesList.size() == 0) {
Toast.makeText(BluetoothChat.this, "没有发现新设备",
Toast.LENGTH_SHORT).show();
mTitle.setText("未连接");
linkDevice();
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
searchDevice();
// Ensure this device is discoverable by others
ensureDiscoverable();
package com.it2388.
* Copyright (C) 2009 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import java.util.UUID;
import android.bluetooth.BluetoothA
import android.bluetooth.BluetoothD
import android.bluetooth.BluetoothServerS
import android.bluetooth.BluetoothS
import android.content.C
import android.os.B
import android.os.H
import android.os.M
import android.util.L
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for incoming
* connections, a thread for connecting with a device, and a thread for
* performing data transmissions when connected.
* *这个类做所有的工作,建立和管理蓝牙 与其他设备的连接。它有一个线程监听 传入的连接,一个用于连接一个设备的线程,和一个 当连接时执行数据传输的线程。
public class BluetoothChatService {
// Debugging
private static final String TAG = "BluetoothChatService";
private static final boolean D =
// Name for the SDP record when creating server socket 对于SDP记录名称创建服务器套接字时
private static final String NAME = "BluetoothChat";
// Unique UUID for this application
private static final UUID MY_UUID = UUID
.fromString("fa87c0d0-afac-11de-8a39-a66");
// Member fields
private final BluetoothAdapter mA
private final Handler mH
private AcceptThread mAcceptT
private ConnectThread mConnectT
private ConnectedThread mConnectedT
private int mS
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing 我们什么都不做
public static final int STATE_LISTEN = 1; // now listening for incoming 现在监听
// connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing
// 启动一个外向
// connection
public static final int STATE_CONNECTED = 3; // now connected to a remote
// 连接到一个远程
* Constructor. Prepares a new BluetoothChat session.
* @param context
The UI Activity Context
* @param handler
A Handler to send messages back to the UI Activity
public BluetoothChatService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler =
* Set the current state of the chat connection
* @param state
An integer defining the current connection state
private synchronized void setState(int state) {
Log.d(TAG, "setState() " + mState + " -& " + state);
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1)
.sendToTarget();
* Return the current connection state.
public synchronized int getState() {
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread =
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread =
// Start the thread to listen on a BluetoothServerSocket
if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
setState(STATE_LISTEN);
* Start the ConnectThread to initiate a connection to a remote device.
* @param device
The BluetoothDevice to connect
public synchronized void connect(BluetoothDevice device) {
Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread =
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread =
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket
The BluetoothSocket on which the connection was made
* @param device
The BluetoothDevice that has been connected
public synchronized void connected(BluetoothSocket socket,
BluetoothDevice device) {
Log.d(TAG, "connected");
// Cancel the thread that completed the connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread =
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread =
// Cancel the accept thread because we only want to connect to one
if (mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread =
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
* Stop all threads
public synchronized void stop() {
Log.d(TAG, "stop");
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread =
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread =
if (mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread =
setState(STATE_NONE);
* Write to the ConnectedThread in an unsynchronized manner
* @param out
The bytes to write
* @see ConnectedThread#write(byte[])
public void write(byte[] out) {
// Create temporary object
ConnectedT
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED)
r = mConnectedT
// Perform the write unsynchronized
r.write(out);
* Indicate that the connection attempt failed and notify the UI Activity.
private void connectionFailed() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "不能连接到设备");
msg.setData(bundle);
mHandler.sendMessage(msg);
* Indicate that the connection was lost and notify the UI Activity.
private void connectionLost() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "设备连接中断");
msg.setData(bundle);
mHandler.sendMessage(msg);
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted (or
* until cancelled).
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerS
public AcceptThread() {
BluetoothServerSocket tmp =
// Create a new listening server socket
tmp = mAdapter
.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
Log.e("sxd", " ======== ufcomm exception =======", e);
mmServerSocket =
public void run() {
Log.d(TAG, "BEGIN mAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket =
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e("sxd", "---& accept socket failed &---", e);
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothChatService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate
// new socket.
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
Log.i(TAG, "END mAcceptThread");
public void cancel() {
Log.d(TAG, "cancel " + this);
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of server failed", e);
* This thread runs while attempting to make an outgoing connection with a
* device. It r the connection either succeeds or
private class ConnectThread extends Thread {
private final BluetoothSocket mmS
private final BluetoothDevice mmD
public ConnectThread(BluetoothDevice device) {
mmDevice =
BluetoothSocket tmp =
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
mmSocket =
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
Log.e("sxd", "链接发生了异常", e);
connectionFailed();
// Close the socket
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG,
"unable to close() socket during connection failure",
// Start the service over to restart listening mode
BluetoothChatService.this.start();
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread =
// Start the connected thread
connected(mmSocket, mmDevice);
public void cancel() {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
* This thread runs during a connection with a remote device. It handles all
* incoming and outgoing transmissions.
* 和已经建立连接的设置进行数据的传输
private class ConnectedThread extends Thread {
private final BluetoothSocket mmS
private final InputStream mmInS
private final OutputStream mmOutS
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket =
InputStream tmpIn =
OutputStream tmpOut =
// Get the BluetoothSocket input and output streams
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
mmInStream = tmpIn;
mmOutStream = tmpO
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
// Keep listening to the InputStream while connected
while (true) {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,
-1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
* Write to the connected OutStream.
* @param buffer
The bytes to write
public void write(byte[] buffer) {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
public void cancel() {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 getunsignedbyte 的文章

 

随机推荐