我在一项活动中启动一项服务,然后我希望该服务在一段时间后自行停止。
我在服务中调用了 stopSelf() 但它不起作用。
如何让服务自行停止?
通过说“不起作用”,我猜你的意思是onDestroy()
- 未调用服务的方法。
我也有同样的问题,因为我bound http://developer.android.com/reference/android/content/Context.html#bindService%28android.content.Intent,%20android.content.ServiceConnection,%20int%29 some 服务连接 http://developer.android.com/reference/android/content/ServiceConnection.html使用标志到服务本身绑定_自动_创建 http://developer.android.com/reference/android/content/Context.html#BIND_AUTO_CREATE。
这会导致服务保持活动状态,直到每个连接都已建立unbound http://developer.android.com/reference/android/content/Context.html#unbindService%28android.content.ServiceConnection%29.
一旦我更改为不使用标志(零),我就可以自行终止服务(stopSelf()
).
示例代码:
final Context appContext = context.getApplicationContext();
final Intent intent = new Intent(appContext, MusicService.class);
appContext.startService(intent);
ServiceConnection connection = new ServiceConnection() {
// ...
};
appContext.bindService(intent, connection, 0);
终止服务(不是进程):
this.stopSelf();
希望有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)