我有示例应用程序来学习绑定服务。它在启动时设置通知。如果我通过单击通知启动应用程序 N 次,那么我也需要单击“返回”按钮 N 次以关闭应用程序并停止服务,这当然是用户预期的错误行为。单击“返回”应停止应用程序。来自http://developer.android.com/guide/components/bound-services.html的 Android 开发人员指南:“多个客户端可以同时连接到服务。但是,系统仅在第一个客户端绑定时调用服务的 onBind() 方法来检索 IBinder。然后系统将相同的 IBinder 传递给绑定的任何其他客户端,而无需调用onBind() 再次。当最后一个客户端与服务解除绑定时,系统会销毁该服务(除非该服务也由 startService() 启动)。所以,我假设每次点击通知都会绑定另一个客户端,然后需要依次解除绑定。我怎样才能摆脱这种不受欢迎的行为?
相关代码:
public class MainActivity extends Activity {
private LocalService mBoundService;
boolean mIsBound = false;
...........
@Override
protected void onStart() {
super.onStart();
if (!mIsBound)
doBindService();
};
.............
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
if (mIsBound) {
int num = mBoundService.getRandomNumber();
Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((LocalService.LocalBinder) service).getService();
// Tell the user about this for our demo.
Toast.makeText(MainActivity.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
...........
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(MainActivity.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
}
}