gpt4 book ai didi

android - 无法解绑服务

转载 作者:行者123 更新时间:2023-11-30 01:29:33 25 4
gpt4 key购买 nike

我启动我的应用程序,开始被调用,执行绑定(bind)服务并触发 onServiceConnected。一切正常。

但是……

当我按回键时,将调用 onStop,我的绑定(bind)变量如预期的那样为真,但永远不会调用 onServiceDisconnected...

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
protected void onStart()
{
Log.e("START", "START");

super.onStart();

// Bind to LocalService
Intent intent = new Intent(this, LocationService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop()
{
Log.e("STOP", "STOP");

super.onStop();

// Unbind from the service
if (mBound)
{
this.unbindService(mConnection);
mBound = false;
}
}

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName className, IBinder service)
{
Log.e("ON SERVICE START", "ON SERVICE START");

// We've bound to LocalService, cast the IBinder and get LocalService instance
LocationService.LocationBinder binder = (LocationService.LocationBinder) service;
mService = binder.getService();
mBound = true;
}

@Override
public void onServiceDisconnected(ComponentName arg0)
{
Log.e("ON SERVICE END", "ON SERVICE END");

mBound = false;
}
};

还有我的服务

// Binder given to clients
private final IBinder mBinder = new LocationBinder();

/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocationBinder extends Binder
{
public LocationService getService()
{
// Return this instance of LocationService so clients can call public methods
return LocationService.this;
}
}

@Override
public IBinder onBind(final Intent intent)
{
Log.e("onBind", "onBind onBind onBind onBind onBind onBind");

return mBinder;
}

/** method for clients */
public int getRandomNumber()
{
return new Random().nextInt(100);
}

最佳答案

每次调用bindService()应与对 unbindService() 的调用配对.绑定(bind)是否有效实际上并不重要。重点是让 Android 知道您不再希望连接处于 Activity 状态。 Android 将负责确定连接当前是否已绑定(bind)和激活并采取适当操作的细节。

最重要的是,您不应在此处有条件地调用 unbindService()。只需始终在 onStop() 中使用与在 onStart() 中调用 bindService() 时使用的相同的 ServiceConnection 调用它。

关于android - 无法解绑服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35961587/

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