在这里,我将为你提供一个完整的 Android 服务示例 (BluetoothService),该服务将连接到蓝牙设备并读取数据。首先,创建一个新的 Android 项目,然后按照以下步骤添加服务和相关代码:
1.创建 BluetoothService 类,该类将处理蓝牙连接和数据读取
创建一个新的 Android 项目,然后将下面代码添加到 BluetoothService.java 文件中。
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class BluetoothService extends Service {
private final IBinder binder = new LocalBinder();
private BluetoothAdapter bluetoothAdapter;
private BluetoothSocket bluetoothSocket;
private InputStream inputStream;
private boolean connected = false;
// UUID 用于标识蓝牙串口服务 (SPP - Serial Port Profile)
private static final UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public class LocalBinder extends Binder {
BluetoothService getService() {
return BluetoothService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public boolean connectToDevice(String deviceAddress) {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(BT_UUID);
bluetoothSocket.connect();
inputStream = bluetoothSocket.getInputStream();
connected = true;
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String readData() {
if (connected) {
try {
byte[] buffer = new byte[1024];
int bytes = inputStream.read(buffer);
return new String(buffer, 0, bytes);
} catch (IOException e) {
e.printStackTrace();
return "Error reading data";
}
} else {
return "Not connected to a Bluetooth device";
}
}
@Override
public void onDestroy() {
super.onDestroy();
try {
if (inputStream != null) {
inputStream.close();
}
if (bluetoothSocket != null) {
bluetoothSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.修改AndroidManifest.xml 文件,添加必要的权限和声明服务
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<application
<!-- ... -->
<service
android:name=".BluetoothService"
android:enabled="true"
android:exported="false" />
</application>
3.创建 MainActivity 类,用于启动服务并读取蓝牙数据
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private BluetoothService bluetoothService;
private boolean serviceBound = false;
private TextView dataTextView;
private Button connectButton;
private Button readDataButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataTextView = findViewById(R.id.dataTextView);
connectButton = findViewById(R.id.connectButton);
readDataButton = findViewById(R.id.readDataButton);
// 绑定服务
Intent serviceIntent = new Intent(this, BluetoothService.class);
bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);
connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 连接到蓝牙设备
if (serviceBound) {
boolean connected = bluetoothService.connectToDevice("蓝牙设备的地址");
if (connected) {
dataTextView.setText("Connected to Bluetooth device.");
} else {
dataTextView.setText("Connection failed.");
}
}
}
});
readDataButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 读取蓝牙数据
if (serviceBound) {
String data = bluetoothService.readData();
dataTextView.setText("Data: " + data);
}
}
});
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
bluetoothService = binder.getService();
serviceBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (serviceBound) {
unbindService(serviceConnection);
}
}
}
4.配置布局文件(省略)
在 res/layout 目录下创建一个 XML 布局文件 (例如 activity_main.xml),并在该布局文件中添加布局元素,比如一些 TextView 和 Button,由于很简单所以就省略了
这样就创建了一个 Android 服务 (BluetoothService),可以在 MainActivity 中启动该服务,连接到蓝牙设备,并读取数据。确保替换 "蓝牙设备的地址" 为你实际要连接的蓝牙设备的地址。在实际应用中,你可能需要添加更多的错误处理和逻辑,以适应你的具体需求。