我编写了一个服务,该服务是从扩展Application的类的onCreate开始的,如下所示。
class Example extends Application {
private BleService bleService;
@Override
public void onCreate() {
super.onCreate();
startBleService(this);
}
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
bleService = ((BleService.LocalBinder) service).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
bleService = null;
}
};
public BleService getBleService(){
return bleService;
}
public void startBleService(Context context) {
context.bindService(new Intent(context, BleService.class), serviceConnection, BIND_AUTO_CREATE);
}
}
public class LocalBinder extends Binder {
public BleService getService() {
return BleService.this;
}
}
当我调试此代码时,调用服务连接,我可以看到bleService已启动且不为null。然而,当我尝试从活动中调用getBleService时,它为null。我已经测试过在实际调用getBleService之前远远分配了bleService,因此它不能成为null的原因。我做错了什么?