java 蓝牙串口_蓝牙串口APP源码

【实例简介】

【实例截图】

b79fd6cd58bf165e1f074b05a7ad4e3e.png

c86f6db1d2d9ce918b890af14179c15b.png

【核心代码】

package cn.jingedawang.bluetoothdemo;

import android.app.Activity;

import android.bluetooth.BluetoothAdapter;

import android.content.Intent;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends Activity {

private static final int REQUEST_ENABLE_BT = 1;

private TextView txtIsConnected;

private EditText edtReceivedMessage;

private EditText edtSentMessage;

private EditText edtSendMessage;

private Button btnSend;

private Button btnPairedDevices;

private BluetoothAdapter mBluetoothAdapter;

private ConnectedThread mConnectedThread;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

txtIsConnected = (TextView) findViewById(R.id.txtIsConnected);

edtReceivedMessage = (EditText) findViewById(R.id.edtReceivedMessage);

edtSentMessage = (EditText) findViewById(R.id.edtSentMessage);

edtSendMessage = (EditText) findViewById(R.id.edtSendMessage);

btnSend = (Button) findViewById(R.id.btnSend);

btnPairedDevices = (Button) findViewById(R.id.btnPairedDevices);

btnPairedDevices.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// 获取蓝牙适配器

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (mBluetoothAdapter == null) {

Toast.makeText(getApplicationContext(), "该设备不支持蓝牙", Toast.LENGTH_SHORT).show();

}

//请求开启蓝牙

if (!mBluetoothAdapter.isEnabled()) {

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

//进入蓝牙设备连接界面

Intent intent = new Intent();

intent.setClass(getApplicationContext(), DevicesListActivity.class);

startActivity(intent);

}

});

//点击【发送】按钮后,将文本框中的文本按照ASCII码发送到已连接的蓝牙设备

btnSend.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (edtSendMessage.getText().toString().isEmpty()) {

return;

}

String sendStr = edtSendMessage.getText().toString();

char[] chars = sendStr.toCharArray();

byte[] bytes = new byte[chars.length];

for (int i=0; i < chars.length; i ) {

bytes[i] = (byte) chars[i];

}

edtSentMessage.append(sendStr);

mConnectedThread.write(bytes);

}

});

}

@Override

protected void onResume() {

super.onResume();

//回到主界面后检查是否已成功连接蓝牙设备

if (BluetoothUtils.getBluetoothSocket() == null || mConnectedThread != null) {

txtIsConnected.setText("未连接");

return;

}

txtIsConnected.setText("已连接");

//已连接蓝牙设备,则接收数据,并显示到接收区文本框

Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what) {

case ConnectedThread.MESSAGE_READ:

byte[] buffer = (byte[]) msg.obj;

int length = msg.arg1;

for (int i=0; i < length; i ) {

char c = (char) buffer[i];

edtReceivedMessage.getText().append(c);

}

break;

}

}

};

//启动蓝牙数据收发线程

mConnectedThread = new ConnectedThread(BluetoothUtils.getBluetoothSocket(), handler);

mConnectedThread.start();

}

}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 蓝牙串口APP程序码是一种用于在移动设备上实现蓝牙串口通信的程序代码。以下是一个简单的示例码: ```java import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; public class BluetoothSerialActivity extends AppCompatActivity { private BluetoothAdapter mBluetoothAdapter; private BluetoothDevice mBluetoothDevice; private BluetoothSocket mBluetoothSocket; private TextView mTextView; private Button mButton; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final int MSG_READ = 0; private static final int MSG_WRITE = 1; private static final int MSG_TOAST = 2; private ConnectedThread mConnectedThread; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_READ: byte[] buffer = (byte[]) msg.obj; String receivedData = new String(buffer); mTextView.setText(receivedData); break; case MSG_WRITE: byte[] writeBuffer = (byte[]) msg.obj; String sentData = new String(writeBuffer); mTextView.setText(sentData); break; case MSG_TOAST: Toast.makeText(getApplicationContext(), msg.getData().getString("toast"), Toast.LENGTH_SHORT).show(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = findViewById(R.id.text_view); mButton = findViewById(R.id.button); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mConnectedThread != null) { mConnectedThread.write("Hello from BluetoothSerialApp".getBytes()); } } }); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothDevice = mBluetoothAdapter.getRemoteDevice("Bluetooth Device Address"); ConnectThread connectThread = new ConnectThread(mBluetoothDevice); connectThread.start(); } private void manageConnectedSocket(BluetoothSocket socket) { mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); } private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; public ConnectThread(BluetoothDevice device) { BluetoothSocket socket = null; try { socket = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { e.printStackTrace(); } mmSocket = socket; } public void run() { mBluetoothAdapter.cancelDiscovery(); try { mmSocket.connect(); } catch (IOException connectException) { connectException.printStackTrace(); try { mmSocket.close(); } catch (IOException closeException) { closeException.printStackTrace(); } return; } manageConnectedSocket(mmSocket); } } private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = mmSocket.getInputStream(); tmpOut = mmSocket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; int bytes; while (true) { try { bytes = mmInStream.read(buffer); mHandler.obtainMessage(MSG_READ, bytes, -1, buffer).sendToTarget(); } catch (IOException e) { e.printStackTrace(); break; } } } public void write(byte[] buffer) { try { mmOutStream.write(buffer); mHandler.obtainMessage(MSG_WRITE, -1, -1, buffer).sendToTarget(); } catch (IOException e) { e.printStackTrace(); mHandler.obtainMessage(MSG_TOAST, "Failed to send data").sendToTarget(); } } } } ``` 这段代码实现了一个简单的蓝牙串口通信APP。首先通过BluetoothAdapter获取BluetoothDevice对象,并使用蓝牙设备地址创建BluetoothSocket。然后创建ConnectThread在后台连接蓝牙设备,并在连接成功后创建ConnectedThread进行数据的读写。当点击按钮时,会将字符串发送给蓝牙设备,并在接收到数据时更新界面上的TextView。 ### 回答2: 蓝牙串口app程序码是一种用于通过蓝牙通信与串口设备进行数据传输的应用程序代码。下面是一个简单的蓝牙串口app程序码示例: ```java import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Handler; import android.os.Message; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; public class BluetoothSerialService { private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private final BluetoothAdapter mAdapter; private final Handler mHandler; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; private static final int STATE_NONE = 0; // 无连接 private static final int STATE_CONNECTING = 1; // 连接中 private static final int STATE_CONNECTED = 2; // 连接成功 public BluetoothSerialService(Handler handler) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mHandler = handler; mState = STATE_NONE; } private synchronized void setState(int state) { mState = state; mHandler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); } public synchronized int getState() { return mState; } public synchronized void connect(BluetoothDevice device) { if (mState == STATE_CONNECTING) { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } mConnectThread = new ConnectThread(device); mConnectThread.start(); setState(STATE_CONNECTING); } public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } mConnectedThread = new ConnectedThread(socket); mConnectedThread.start(); Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME); mHandler.sendMessage(msg); setState(STATE_CONNECTED); } public synchronized void stop() { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } setState(STATE_NONE); } public void write(byte[] out) { ConnectedThread r; synchronized (this) { if (mState != STATE_CONNECTED) return; r = mConnectedThread; } r.write(out); } private void connectionFailed() { setState(STATE_NONE); Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST); mHandler.sendMessage(msg); } private void connectionLost() { setState(STATE_NONE); Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST); mHandler.sendMessage(msg); } private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { e.printStackTrace(); } mmSocket = tmp; } public void run() { mAdapter.cancelDiscovery(); try { mmSocket.connect(); } catch (IOException connectException) { try { mmSocket.close(); } catch (IOException closeException) { closeException.printStackTrace(); } connectionFailed(); return; } synchronized (BluetoothSerialService.this) { mConnectThread = null; } connected(mmSocket, mmDevice); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; private byte[] mmBuffer; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { mmBuffer = new byte[1024]; int numBytes; while (true) { try { numBytes = mmInStream.read(mmBuffer); byte[] readBuffer = new byte[numBytes]; System.arraycopy(mmBuffer, 0, readBuffer, 0, numBytes); mHandler.obtainMessage(MainActivity.MESSAGE_READ, numBytes, -1, readBuffer).sendToTarget(); } catch (IOException e) { e.printStackTrace(); connectionLost(); break; } } } public void write(byte[] buffer) { try { mmOutStream.write(buffer); mHandler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); } catch (IOException e) { e.printStackTrace(); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 以上是一个简单的蓝牙串口app程序的示例代码,可以利用该代码实现与串口设备之间的数据传输。其中,主要包括`BluetoothSerialService`类用于实现蓝牙连接和数据传输的相关方法,`ConnectThread`类用于管理蓝牙连接,`ConnectedThread`类用于管理蓝牙数据的读写。此外,代码还包括一些状态常量和相应的处理方式。请注意,这只是一个简单的示例代码,实际应用中还需根据具体需求进行相应的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值