Android蓝牙通信:从主Activity调用MyBluetoothService的write方法传参指导
搞定Android蓝牙服务发送字符串的步骤
嘿,我来帮你把字符串从主Activity传到MyBluetoothService的write方法,再发送给蓝牙设备!结合官方教程的MyBluetoothService类,咱们一步步来:
1. 先确认Service里的write方法
官方教程里的MyBluetoothService应该已经有一个接收byte数组的write方法,大概长这样:
public class MyBluetoothService { // ... 其他成员变量和方法 ... public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { // 这里可以加异常处理,比如记录日志或者通知Activity发送失败 Log.e("BluetoothService", "发送数据失败: " + e.getMessage()); } } }
如果你的类里还没有这个方法,先把它补上——因为蓝牙Socket的OutputStream只能写byte数组,所以我们需要把字符串转成byte数组再传入。
2. 在Activity中绑定Service并获取实例
要调用Service的write方法,你得先拿到Service的引用。官方教程用的是LocalBinder方式绑定,咱们照着来:
第一步:在Activity里定义成员变量
public class MainActivity extends AppCompatActivity { private MyBluetoothService mBluetoothService; private boolean mIsServiceBound = false; // 标记Service是否已绑定 // ... 其他控件变量 ... }
第二步:实现ServiceConnection接口
这个接口用来监听Service的绑定状态,拿到Service实例:
private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // 从Binder中获取Service实例 MyBluetoothService.LocalBinder binder = (MyBluetoothService.LocalBinder) service; mBluetoothService = binder.getService(); mIsServiceBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mIsServiceBound = false; mBluetoothService = null; } };
第三步:绑定Service
在Activity的onCreate或者合适的生命周期方法里绑定Service(比如用户点击连接蓝牙后):
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 绑定Service Intent serviceIntent = new Intent(this, MyBluetoothService.class); bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE); }
别忘了在onDestroy里解绑:
@Override protected void onDestroy() { super.onDestroy(); if (mIsServiceBound) { unbindService(mServiceConnection); mIsServiceBound = false; } }
3. 把字符串转成byte数组,调用write方法发送
比如你有一个输入框和发送按钮,点击按钮时把输入的字符串转成byte数组,再调用Service的write方法:
布局里的控件(参考)
<EditText android:id="@+id/et_input_message" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入要发送的内容"/> <Button android:id="@+id/btn_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送"/>
Activity里的点击事件处理
Button sendBtn = findViewById(R.id.btn_send); EditText inputEt = findViewById(R.id.et_input_message); sendBtn.setOnClickListener(v -> { // 先检查Service是否绑定且蓝牙已连接 if (mBluetoothService != null && mIsServiceBound && mBluetoothService.isConnected()) { String message = inputEt.getText().toString().trim(); if (!message.isEmpty()) { // 把字符串转成UTF-8编码的byte数组(避免乱码) byte[] sendData = message.getBytes(StandardCharsets.UTF_8); // 调用Service的write方法发送 mBluetoothService.write(sendData); // 发送后清空输入框 inputEt.setText(""); } else { Toast.makeText(this, "请输入要发送的内容", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "蓝牙未连接或服务未就绪", Toast.LENGTH_SHORT).show(); } });
这里我加了一个isConnected()方法的检查——你可以在MyBluetoothService里加一个成员变量private boolean mIsConnected = false;,在connected方法(就是建立Socket连接的那个方法)里把它设为true,断开连接时设为false,然后提供一个公开的getter方法:
public boolean isConnected() { return mIsConnected; }
几个关键注意点
- 编码统一:一定要指定编码(比如UTF-8),不然不同设备之间可能会出现乱码。
- 异常处理:在Service的write方法里要捕获IOException,比如设备突然断开连接的情况,还可以通过广播或者回调通知Activity发送结果。
- 生命周期管理:记得在Activity销毁时解绑Service,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Miles Garceau
相关产品推荐
相关产品推荐

