Android 连接2个蓝牙设备
我正在尝试制作一个使用蓝牙的应用程序。它非常简单,但我一直在连接设备 到目前为止,我已经制作了两个列表视图,一个显示配对的设备,另一个显示找到的设备。我不知道套接字是如何工作的,以及如何制作设备服务器或客户端 有人能给我解释一下,或者至少告诉我如何处理我已经复制的代码吗 我已经阅读了所有我能找到的教程,但我仍然不理解。蓝牙聊天示例非常混乱,我是android编程的初学者,并且没有真正学习太多java 代码如下:Android 连接2个蓝牙设备,android,sockets,bluetooth,server,client,Android,Sockets,Bluetooth,Server,Client,我正在尝试制作一个使用蓝牙的应用程序。它非常简单,但我一直在连接设备 到目前为止,我已经制作了两个列表视图,一个显示配对的设备,另一个显示找到的设备。我不知道套接字是如何工作的,以及如何制作设备服务器或客户端 有人能给我解释一下,或者至少告诉我如何处理我已经复制的代码吗 我已经阅读了所有我能找到的教程,但我仍然不理解。蓝牙聊天示例非常混乱,我是android编程的初学者,并且没有真正学习太多java 代码如下: public class ConnectThread extends Thread{
public class ConnectThread extends Thread{
BluetoothDevice device;
private BluetoothSocket socket;
ConnectThread(){
connect(device, MY_UUID);
}
public boolean connect(BluetoothDevice bTDevice, UUID mUUID) {
BluetoothSocket temp = null;
try {
temp = bTDevice.createRfcommSocketToServiceRecord(mUUID);
} catch (IOException e) {
Log.d("CONNECTTHREAD","Could not create RFCOMM socket:" + e.toString());
return false;
}
try {
socket.connect();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not connect: " + e.toString());
try {
socket.close();
} catch(IOException close) {
Log.d("CONNECTTHREAD", "Could not close connection:" + e.toString());
return false;
}
}
return true;
}
public boolean cancel() {
try {
socket.close();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not close connection:" + e.toString());
return false;
}
return true;
}
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetooth.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}}
这是xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:baselineAligned="false">
<ListView
android:layout_width="170dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:background="@drawable/lviewbg"
android:id="@+id/paired_devies">
</ListView>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="fill_horizontal"
android:background="@drawable/lviewbg"
android:id="@+id/new_devices">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:id="@+id/discover"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#aa0000ff"
android:text="@string/disc"
style="?android:attr/buttonBarButtonStyle"
/>
<Button
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#aa0000ff"
android:text="@string/discoverable"
android:onClick="makeDiscoverable"
style="?android:attr/buttonBarButtonStyle"
/>
</LinearLayout>
</LinearLayout>
如果需要,以下是代码的其余部分:
package com.example.user.broj;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
public class BluetoothDevices extends AppCompatActivity{
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
BluetoothDevice device;
static int REQUEST_ENABLE_BT = 1;
static int DISCOVERABLE_BT_REQUEST_CODE = 1;
static int DISCOVERABLE_DURATION = 120;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
//This is used for connecting devices
static final String NAME = "BluetoothGame";
static final UUID MY_UUID = UUID.fromString("ae19c8fa-9b60-11e5-8994-feff819cdc9f");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
Button scanButton = (Button) findViewById(R.id.discover);
scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doDiscovery();
view.setClickable(false);
}
});
//enabling bluetooth
if(!bluetooth.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
}
//arrayadapters for paired and new devices list views
mPairedDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
//listview for paired devices
ListView deviceList = (ListView) findViewById(R.id.paired_devies);
deviceList.setAdapter(mPairedDevicesArrayAdapter);
deviceList.setOnItemClickListener(mDeviceClickListener);
//listview for new devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
bluetooth = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
if (pairedDevices.size() > 0) {
//findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
//button onClick for making the device discoverable
public void makeDiscoverable(View view) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DISCOVERABLE_BT_REQUEST_CODE){
if (resultCode == DISCOVERABLE_DURATION){
Toast.makeText(getApplicationContext(), "Your device is now discoverable by other devices for " +
DISCOVERABLE_DURATION + " seconds",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Fail to enable discoverability on your device.",
Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (bluetooth != null) {
bluetooth.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
// findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (bluetooth.isDiscovering()) {
bluetooth.cancelDiscovery();
}
// Request discover from BluetoothAdapter
bluetooth.startDiscovery();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetooth.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Button scanButton = (Button) findViewById(R.id.discover);
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
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) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
scanButton.setClickable(true);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
package com.example.user.broj;
导入android.app.Activity;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothServerSocket;
导入android.bluetooth.BluetoothSocket;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.os.Bundle;
导入android.support.v7.app.AppActivity;
导入android.util.Log;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.ListView;
导入android.widget.TextView;
导入android.widget.Toast;
导入java.io.IOException;
导入java.util.Set;
导入java.util.UUID;
公共类BluetoothDevices扩展了AppCompative活动{
私有静态最终字符串标记=“DeviceListActivity”;
私有静态最终布尔值D=true;
蓝牙设备;
静态整数请求\启用\ BT=1;
静态int可发现_BT_请求_代码=1;
静态int可发现_持续时间=120;
公共静态字符串EXTRA\u DEVICE\u ADDRESS=“DEVICE\u ADDRESS”;
私有BluetoothAdapter bluetooth=BluetoothAdapter.getDefaultAdapter();
阵列适配器MPairedevicesArrayaAdapter;
专用阵列适配器mNewDevicesArrayAdapter;
//这用于连接设备
静态最终字符串NAME=“BluetoothGame”;
静态最终UUID MY_UUID=UUID.fromString(“ae19c8fa-9b60-11e5-8994-feff819cdc9f”);
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
按钮扫描按钮=(按钮)findViewById(R.id.discover);
scanButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图){
doDiscovery();
视图。可点击设置(错误);
}
});
//启用蓝牙
如果(!bluetooth.isEnabled()){
意向btIntent=新意向(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(btIntent、REQUEST\u ENABLE\u BT);
}
//配对设备和新设备列表视图的阵列适配器
MPairedDeviceArrayAdapter=新的ArrayAdapter(这个,R.layout.device\u名称);
mNewDevicesArrayAdapter=新的ArrayAdapter(这个,R.layout.device_名称);
//配对设备的列表视图
ListView设备列表=(ListView)findViewById(R.id.paired_设备);
deviceList.setAdapter(MPairedDeviceArrayaAdapter);
deviceList.setOnItemClickListener(mDeviceClickListener);
//新设备的列表视图
ListView新设备ListView=(ListView)findViewById(R.id.new_设备);
setAdapter(mNewDevicesArrayAdapter);
setOnItemClickListener(mDeviceClickListener);
IntentFilter筛选器=新的IntentFilter(BluetoothDevice.ACTION\u已找到);
此。注册表接收程序(mReceiver,过滤器);
过滤器=新的IntentFilter(BluetoothAdapter.ACTION\u DISCOVERY\u FINISHED);
此。注册表接收程序(mReceiver,过滤器);
bluetooth=BluetoothAdapter.getDefaultAdapter();
Set pairedDevices=bluetooth.getBondedDevices();
如果(pairedDevices.size()>0){
//findViewById(R.id.title\u paired\u devices).setVisibility(View.VISIBLE);
用于(蓝牙设备:pairedDevices){
MPairedDeviceArrayaAdapter.add(device.getName()+“\n”+device.getAddress());
}
}否则{
String NodeDevices=getResources().getText(R.String.none_paired).toString();
MPairedDeviceArrayaAdapter.add(节点设备);
}
}
//单击按钮onClick可发现设备
公共void使可发现(视图){
Intent discoverableIntent=新意图(BluetoothAdapter.ACTION\u REQUEST\u DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA\u DISCOVERABLE\u DURATION,DISCOVERABLE\u DURATION);
startActivityForResult(可发现意图、可发现请求代码);
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
if(requestCode==可发现的请求码){
if(resultCode==可发现的\u持续时间){
Toast.makeText(getApplicationContext(),“您的设备现在可被其他设备发现”+
可发现的_持续时间+“秒”,
吐司。长度(短)。show();
}否则{
Toast.makeText(getApplicationContext(),“无法在设备上启用可发现性。”,
吐司。长度(短)。show();
}
}
}
@凌驾
受保护的空onDestroy(){
s
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
InputStream is1;
OutputStream os1;
BluetoothAdapter bluetoothAdapter = null;
BluetoothSocket socket = null;
class UserInterface extends Thread {
BluetoothDevice bdDevice;
public UserInterface() {
bdDevice = your pair device;
}
@Override
public void run() {
Looper.prepare();
try {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
if (socket != null && socket.isConnected()) {
is1.close();
os1.close();
socket.close();
}
try {
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {
Log.e("", "Error creating socket");
}
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
try {
socket.connect();
Log.e("", "Connected Rfcomm");
} catch (IOException e) {
Log.e("", e.getMessage());
try {
Log.e("", "trying fallback...");
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
socket.connect();
Log.e("", "Connected serial UDID");
} catch (Exception e2) {
Log.e("", "Couldn't establish Bluetooth connection!");
}
}
if (socket.isConnected()) {
// dismiss Progress Dialog
os1 = socket.getOutputStream();
is1 = socket.getInputStream();
Log.i("TAG", "Socket Connected");
//code after socket connect
} else {
// dismiss Progress Dialog
showProgressDialogToast("Please restart bluetooth Device");
closeSocket();
Log.i("TAG", "Socket Disconnected");
}
Log.i("Log", "Removed" + bdDevice.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Log", "Under Catch of thread");
e.printStackTrace();
// dismiss Progress Dialog
}
}
}
UserInterface userInterface = new UserInterface();
userInterface.start();