gpt4 book ai didi

java - 如何为android绑定(bind)多个不同的服务?

转载 作者:行者123 更新时间:2023-11-30 12:05:15 24 4
gpt4 key购买 nike

我想在 Activity 开始时启动 2 个服务,但只有第一个启动,第二个在 bindService() 处失败。当我想对服务执行某些操作时没有错误,它给了我一个空指针。我也尝试等待做某事,但服务从未启动。

这两个服务非常相似,我只想知道实现有什么问题。我尝试调试 bindservice() 函数在 startSoundmanagerService 返回 0,这可能是问题的根源,但我不知道为什么。

public class SimulationActivity extends AppCompatActivity {

BluetoothService BService;
boolean mBound = false;
SoundManager SService;
boolean sBound = false;

@Override
protected void onStart() {
super.onStart();
if (bluetoothAdapter.isEnabled()) {
setStatusText("Bluetooth on");
}
else {
setStatusText("Bluetooth off");
}
if(!mBound) {
startServer();
}
conStatImageView.setImageResource(R.drawable.connection_off);
if(!sBound){
startSoundManagerService();
}

@Override
protected void onStop() {
super.onStop();
if(mBound) {
unbindService(bConnection);
mBound = false;
}
if(sBound){
unbindService(sConnection);
sBound = false;
}


}

private ServiceConnection bConnection = new ServiceConnection() {

@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
BluetoothService.LocalBinder binder =
(BluetoothService.LocalBinder) service;

BService = binder.getService();
mBound = true;
}

@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};


private ServiceConnection sConnection = new ServiceConnection() {

@Override
public void onServiceConnected(ComponentName className,
IBinder service) {

SoundManager.LocalBinder binder = (SoundManager.LocalBinder) service;
SService = binder.getService();
sBound = true;
}

@Override
public void onServiceDisconnected(ComponentName arg0) {
sBound = false;
}


public void startServer(){

if (bluetoothAdapter == null) {
Log.d("tag","Device doesn't support Bluetooth") ;
}

if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
if(bluetoothAdapter.isEnabled()){
startBluetoothservice();
}

}

private void startBluetoothservice(){

Intent intent = new Intent (this,BluetoothService.class);
bindService(intent, bConnection, Context.BIND_AUTO_CREATE);
Log.i(TAG,"Trying to start bluetoothservice");
}
private void startSoundManagerService(){

Intent intent = new Intent (this,SoundManager.class);
bindService(intent, sConnection, Context.BIND_AUTO_CREATE);
Log.i(TAG,"Trying to start soundservice");

}

那么如何在 1 个 Activity 中实现 2 个不同的服务?

编辑解决方案:我忘记在 list 文件中注册服务。 ;)

最佳答案

我找到了解决方案:我忘记在 list 中注册第二个服务。就这些;)

关于java - 如何为android绑定(bind)多个不同的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56434740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com