我正在为我的应用程序编写蓝牙服务。我对Android中的服务知之甚少,但我设法启动并以我想要的方式使用它。
我的问题刚刚开始,当我尝试使用来自Activity的onCreate()
方法的服务中的函数时(它没有时间来绑定服务)。
我将代码构建为3个类:
BluetoothService: 实现服务的类
public class BluetoothService extends Service implements IScanService {
private final IBinder bluetoothBinder = new BluetoothBinder();
@Override
public IBinder onBind(Intent intent) {
return bluetoothBinder;
}
public class BluetoothBinder extends Binder {
public BluetoothService getService() {
return BluetoothService.this;
}
}
// Other functions
}
BluetoothActivity: 处理蓝牙服务连接的抽象类(用于可重用性)。
public abstract class BluetoothActivity extends AppCompatActivity {
protected BluetoothService bluetoothService;
protected volatile Boolean isBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Connecting to the service
Intent intent = new Intent(this, BluetoothService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
BluetoothService.BluetoothBinder binder = (BluetoothService.BluetoothBinder) service;
bluetoothService = binder.getService();
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName className) {
isBound = false;
}
};
// Other functions
}
ScanActivity: 从BluetoothActivity扩展并在' onCreate()'上使用BluetoothService方法的活动类。
变量' isBound'旨在用于了解服务是否受约束(或者我们是否必须等待)。
我尝试了什么:
所以我的问题是我如何等待'onCreate()'方法直到' isBound'是真的吗?
答案 0 :(得分:0)
我刚刚意识到我可以在onServiceConnected()
上创建两个函数,并在onServiceDisconnected()
和private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
BluetoothActivity.this.onServiceConnected(name, (BluetoothService.BluetoothBinder) binder);
}
@Override
public void onServiceDisconnected(ComponentName name) {
BluetoothActivity.this.onServiceDisconnected(name);
}
};
protected void onServiceConnected(ComponentName name, BluetoothService.BluetoothBinder binder){
bluetoothService = binder.getService();
}
protected void onServiceDisconnected(ComponentName name){
bluetoothService = null;
}
上调用它们:
@Override
protected void onServiceConnected(ComponentName name, BluetoothService.BluetoothBinder binder) {
super.onServiceConnected(name, binder);
//TODO
}
@Override
protected void onServiceDisconnected(ComponentName name) {
// TODO
super.onServiceDisconnected(name);
}
然后在扩展类上覆盖它们:
{{1}}