我是一个初学者,他编写了一个简单的程序来演示服务的工作方式。
.....
toStartService = new Intent(this, SimpleService.class);
sc = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(MoreService.this,"SC: Binded", Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(MoreService.this,"SC: Unbinded", Toast.LENGTH_SHORT).show();
}
};
startService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MoreService.this,"Starting Service", Toast.LENGTH_SHORT).show();
startService(toStartService);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(toStartService);
}
});
bindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((isBound = bindService(toStartService, sc, BIND_AUTO_CREATE))) {
}
}
});
unbindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isBound) {
unbindService(sc);
isBound = false;
}
}
});
}
为什么不传递sc变量(在bindService()上)调用sc.onServiceConnected()方法?
代码有什么问题?
我满足以下条件:
当我按[startService]
服务启动得很好,然后
[stopService]服务停止得很好。
当我按[startService]时,[bindService]则不执行任何操作,也没有[unbindService]。
当我按[bindService]时,其创建了服务,[stopService]没有起作用。 我按[unbindService],服务正在调用onDestroy()方法。
解除绑定后,为什么bindService创建的服务会被破坏? 我尝试使用startService启动服务,但无法绑定。
哎呀,抱歉,如果我错了。
我也有完全一样的问题。 现在,我明白了为什么很多人讨厌Java。。。无论如何,当您说"代码有什么问题"时要非常小心,因为该网站上有数以百万计的冒充"态度警察",除了回避诸如此类的问题外,什么也不做 你的。
这是所有这些方法的设计行为。 例如,在根据文档的bindService(Intent service, ServiceConnection conn, int flags)方法中,该服务仅在存在调用上下文的情况下才运行:
The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.
对于unbindService (ServiceConnection conn),文档说:
Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time.
在startService (Intent service)文档中说:
Using startService() overrides the default service lifetime that is managed by bindService(Intent, ServiceConnection, int): it requires the service to remain running until stopService(Intent) is called, regardless of whether any clients are connected to it. Note that calls to startService() are not nesting: no matter how many times you call startService(), a single call to stopService(Intent) will stop it.
谢谢,"该服务仅在调用上下文存在的情况下才能运行",那么我如何绑定到已经在运行的服务?
如果该服务是由startService启动的,则可以绑定到该服务,并且在取消绑定后它将保持运行,但是,如果该服务是由bindService启动的,则只要存在调用上下文,它就将保持运行。
哦,我只是将mBinder插入服务的onBind方法中,然后ServiceConnection现在可以工作了! 为什么会这样?