1. service程序编写
public class BluetoothService extends Service {
private ICallBack iCallBack;
private IBinder binder = new BluetoothService.LocalBinder();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
public class LocalBinder extends Binder {
public BluetoothService getService() {
return BluetoothService.this;
}
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
2. activity中调用
public BluetoothService mBluetoothService;
2.1 service的连接与断开
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mBluetoothService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBluetoothService = ((BluetoothService.LocalBinder) service).getService();
Log.i("huzh", "onServiceConnected");
}
};
2.2 启动service
Intent intent = new Intent(this, BluetoothService.class);
startService(intent);
getApplicationContext().bindService(intent, connection, Context.BIND_AUTO_CREATE);
蓝牙服务编程指南
本文详细介绍了一个基于Android平台的蓝牙服务编程实例。通过一个具体的BluetoothService类,展示了如何创建并实现服务端与客户端的连接,包括服务注册、绑定、启动及断开等关键步骤。同时,也介绍了在Activity中如何调用服务,实现与蓝牙设备的数据交互。
1万+

被折叠的 条评论
为什么被折叠?



