我有开关偏好设置,应该启动/停止一些内部服务工作。已按预期在onServiceConnected
中初始化了服务API(活页夹)。但是,当我转到首选项屏幕时,取消绑定并停止服务。
我正在使用LiveData
处理主要活动的偏好更改。但是问题是,当它再次变为活动状态并调用观察者时,onServiceConnected
仍然没有被调用,ServiceApi(Binder)
观察者中启动/停止smth所需的LiveData
尚未初始化。
通过偏好更改在Android服务中进行更改的正确方法是什么?
public class CameraServiceConnection implements ServiceConnection {
public CameraServiceApi cameraServiceApi;
@Override
public void onServiceConnected(ComponentName name, IBinder service){
cameraServiceApi = (CameraServiceApi) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
cameraServiceApi = null;
}
@Override
public void onBindingDied(ComponentName name) {
cameraServiceApi = null;
}
}
In MainActivity:
LiveData<Boolean> fpsEnabled = new SharedPreferenceBooleanLiveData(prefs, "fpsEnabled", false);
fpsEnabled.observe(this, this::onFpsEnabled);
private void onFpsEnabled(boolean enabled) {
// cameraServiceApi is always null here! will be initialized later
if (cameraServiceConnection.cameraServiceApi != null) {
if(enabled) {
cameraServiceConnection.cameraServiceApi.init();
}
}
}