android 绑定服务启动,在Android上绑定服务与启动服务以及如何执行这两个

我在问一个已经(部分地在我的脑海中)写出here和here的棘手问题。比方说,在很多例子中,我们想要创建一个音乐应用程序,使用(比如说)一个活动和一个服务。我们希望服务在活动停止或销毁时保留。这种生命周期提出了一种启动的服务:在Android上绑定服务与启动服务以及如何执行这两个

服务的“启动”,当一个应用程序组件(如 活动)通过调用startService启动它()。一旦启动,服务 可以在后台无限期地运行,即使 开始被销毁

好的,但我们也希望能够与服务进行通信,所以我们需要一个服务绑定组件。没问题,我们有两个绑定,并开始服务为this answer suggests:

在活动启动(或一些其他点),我们称之为startService()

到目前为止这么好,但是一个问题来自事实,即当活动开始时,我们不知道服务是否在附近。它可能已经开始或者它可能不是。答案可能是这样的:

如果失败,然后开始使用startService()的服务,然后绑定到它。

这个想法的前提是文档的特定读数bindService():

连接到应用程序服务,如果需要创建它。

如果零标志的意思是“服务不是真的需要”比我们没有问题。因此,我们尝试这样的事情使用下面的代码:

private void connectToService() {

Log.d("MainActivity", "Connecting to service");

// We try to bind to an existing service

Intent bindIntent = new Intent(this, AccelerometerLoggerService.class);

boolean bindResult = bindService(bindIntent, mConnection, 0);

if (bindResult) {

// Service existed, so we just bound to it

Log.d("MainActivity", "Found a pre-existing service and bound to it");

} else {

Log.d("MainActivity", "No pre-existing service starting one");

// Service did not exist so we must start it

Intent startIntent = new Intent(this, AccelerometerLoggerService.class);

ComponentName startResult = startService(startIntent);

if (startResult==null) {

Log.e("MainActivity", "Unable to start our service");

} else {

Log.d("MainActivity", "Started a service will bind");

// Now that the service is started, we can bind to it

bindService(bindIntent, mConnection, 0);

if (!bindResult) {

Log.e("MainActivity", "started a service and then failed to bind to it");

} else {

Log.d("MainActivity", "Successfully bound");

}

}

}

}

而且我们得到了一个成功的结合每次都是:

04-23 05:42:59.125: D/MainActivity(842): Connecting to service

04-23 05:42:59.125: D/MainActivity(842): Found a pre-existing service and bound to it

04-23 05:42:59.134: D/MainActivity(842): onCreate

全球问题是“我误解必然与启动服务,以及如何使用它们?“更具体的问题是:

是否正确理解文档认为零标志传递给bindService()表示“不启动服务”?如果没有,没有启动服务,是否没有办法拨打bindService()?

即使服务未运行,为什么bindService()返回true?在这种情况下,根据Log调用,似乎服务已经启动。

如果有以前的一点是bindService()正确/预期的行为,有一种解决方法(即一定程度上保证startService只调用如果服务没有运行?)

附:我已经从我自己的代码中解决了问题:不管怎样,我都会发出startService()调用,因为重复的startService()会被忽略。不过,我仍然想更好地理解这些问题。

+0

我不完全理解这是如何工作的,但[this](http://www.101apps.co.za/articles/bound-services-what-you-should-know.html)和[this] (http://www.101apps.co.za/articles/binding-to-a-service-a-tutorial.html)可能会对你有所帮助。 –

2015-05-27 14:11:28

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值