Java 尝试使用蓝牙,但对处理程序缺乏了解
我的最后一个问题结束了,因为不够集中。我的目标是向蓝牙模块hc-06发送一个阵列来驾驶Arduino。我进行了研究并访问了此页面(以及其他页面): 我希望有一个解释能让以下代码正常工作:Java 尝试使用蓝牙,但对处理程序缺乏了解,java,android,bluetooth,Java,Android,Bluetooth,我的最后一个问题结束了,因为不够集中。我的目标是向蓝牙模块hc-06发送一个阵列来驾驶Arduino。我进行了研究并访问了此页面(以及其他页面): 我希望有一个解释能让以下代码正常工作: import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.Blueto
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class multiplayerConnect extends AppCompatActivity {
public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;
String bluetooth_message="00";
@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
@Override
public void handleMessage(Message msg_type) {
super.handleMessage(msg_type);
switch (msg_type.what){
case MESSAGE_READ:
byte[] readbuf=(byte[])msg_type.obj;
String string_recieved=new String(readbuf);
//do some task based on received string
break;
case MESSAGE_WRITE:
if(msg_type.obj!=null){
ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
connectedThread.write(bluetooth_message.getBytes());
}
break;
case CONNECTED:
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
break;
case CONNECTING:
Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
break;
case NO_SOCKET_FOUND:
Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplayer_bluetooth);
initialize_layout();
initialize_bluetooth();
start_accepting_connection();
initialize_clicks();
}
public void start_accepting_connection()
{
//call this on button click as suited by you
AcceptThread acceptThread = new AcceptThread();
acceptThread.start();
Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Object[] objects = set_pairedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) objects[position];
ConnectThread connectThread = new ConnectThread(device);
connectThread.start();
Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
}
});
}
public void initialize_layout()
{
lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
lv_paired_devices.setAdapter(adapter_paired_devices);
}
public void initialize_bluetooth()
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
finish();
}
//Add these permisions before
// <uses-permission android:name="android.permission.BLUETOOTH" />
// <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
// <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else {
set_pairedDevices = bluetoothAdapter.getBondedDevices();
if (set_pairedDevices.size() > 0) {
for (BluetoothDevice device : set_pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
}
}
}
}
public class AcceptThread extends Thread
{
private final BluetoothServerSocket serverSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
} catch (IOException e) { }
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null)
{
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(CONNECTED).sendToTarget();
}
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mHandler.obtainMessage(CONNECTING).sendToTarget();
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// bluetooth_message = "Initial message"
// mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
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;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[2]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
导入android.annotation.SuppressLint;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothServerSocket;
导入android.bluetooth.BluetoothSocket;
导入android.content.Intent;
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.Message;
导入android.support.annotation.Nullable;
导入android.support.v7.app.AppActivity;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.ArrayAdapter;
导入android.widget.ListView;
导入android.widget.Toast;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.ArrayList;
导入java.util.Set;
导入java.util.UUID;
公共类多层连接扩展AppCompatActivity{
公共静态最终整数请求\u ENABLE\u BT=1;
ListView lv_配对设备;
设置设备;
阵列适配器配对设备;
蓝牙适配器;
公共静态最终UUID MY_UUID=UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
公共静态最终整型消息_READ=0;
公共静态最终int消息_WRITE=1;
公共静态最终int连接=2;
公共静态最终连接int=3;
公共静态最终输入未找到插座=4;
字符串bluetooth_message=“00”;
@SuppressLint(“HandlerLeak”)
Handler mHandler=新处理程序()
{
@凌驾
公共无效handleMessage(消息消息类型){
super.handleMessage(msg_类型);
开关(msg_类型。什么){
案例信息如下:
字节[]readbuf=(字节[])msg_type.obj;
String String_received=新字符串(readbuf);
//根据收到的字符串执行一些任务
打破
案例信息\u写入:
if(msg_type.obj!=null){
ConnectedThread ConnectedThread=新的ConnectedThread((BluetoothSocket)msg_type.obj);
connectedThread.write(bluetooth_message.getBytes());
}
打破
有关个案:
Toast.makeText(getApplicationContext(),“Connected”,Toast.LENGTH\u SHORT.show();
打破
案例连接:
Toast.makeText(getApplicationContext(),“连接…”,Toast.LENGTH\u SHORT.show();
打破
未找到外壳插座:
Toast.makeText(getApplicationContext(),“未找到套接字”,Toast.LENGTH_SHORT.show();
打破
}
}
};
@凌驾
创建时受保护的void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplayer_bluetooth);
初始化_布局();
初始化蓝牙();
启动_接受_连接();
初始化_单击();
}
公共无效开始\u接受\u连接()
{
//根据您的需要单击此按钮
AcceptThread AcceptThread=新的AcceptThread();
acceptThread.start();
Toast.makeText(getApplicationContext(),“接受”,Toast.LENGTH\u SHORT.show();
}
公共无效初始化\u单击()
{
lv_paired_devices.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id)
{
Object[]objects=set_pairedDevices.toArray();
BluetoothDevice=(BluetoothDevice)对象[位置];
ConnectThread ConnectThread=新的ConnectThread(设备);
connectThread.start();
Toast.makeText(getApplicationContext(),“device choosen”+device.getName(),Toast.LENGTH_SHORT).show();
}
});
}
公共空间布局()
{
lv_paired_devices=(ListView)findViewById(R.id.lv_paired_devices);
adapter\u paired\u devices=new ArrayAdapter(getApplicationContext(),R.layout.support\u simple\u spinner\u dropdown\u项目);
lv_配对设备。setAdapter(适配器配对设备);
}
公共无效初始化\u蓝牙()
{
bluetoothAdapter=bluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter==null){
//设备不支持蓝牙
Toast.makeText(getApplicationContext(),“您的设备不支持蓝牙。您可以作为单人播放器播放”,Toast.LENGTH_SHORT).show();
完成();
}
//在之前添加这些权限
//
//
//
//
如果(!bluetoothAdapter.isEnabled()){
Intent enablebintent=新意图(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(启用BTIntent、请求\启用\ BT);
}
否则{
set_pairedDevices=bluetoothAdapter.getBondedDevices();
if(set_paireDevices.size()>0){
用于(蓝牙设备:set_pairedDevices){
字符串deviceName=device.getName();
String deviceHardwareAddress=device.getAddress();//MAC地址
适配器\u paired\u devices.add(device.getName()+“\n”+device.getAddress());
}
}
}
}
公共类AcceptThread扩展线程
{
私有最终BluetoothServerSocket服务器套接字;
公共线程(){
BluetoothServerSocket tmp=null;
试一试{
//MY_UUID是应用程序的UUID字符串,客户端代码也使用它
tmp=bluetoothAdapter.listenUsingRfcommWithServiceRecord(“名称”,我的UUID);
}捕获(IOE){}
serverSocket=tmp;
}
公开募捐{
BluetoothSocket=null;
//继续侦听,直到发生异常或返回套接字
while(true){
试一试{
socket=serverSocket.accept();
}捕获(IOE异常){