)方法; 2.如果service已处于运行中,调用startService()不会执行onCreate()方法,只执行onStartCommand()方法。 也就是说,onCreate()只会在第一次创建service时候调用,多次执行startService()不会重复调用onCreate(),此方法适合完成一些初始化工作。
onStartCommand() 如果多次执行了Context的startService()方法,那么Service的onStartCommand()方法也会相应的多次调用。onStartCommand()方法很重要,我们在该方法中根据传入的Intent参数进行实际的操作,比如会在此处创建一个线程用于下载数据或播放音乐等。
onBind() Service中的onBind()方法是抽象方法,Service类本身就是抽象类,所以onBind()方法是必须重写的,即使我们用不到。
onDestroy() 在销毁的时候会执行Service的该方法。
这几个方法都是回调方法,且在主线程中执行,由Android操作系统在合适的时机调用。
注意:每个Service
必须在manifest
中 通过<service>来声明。
<service android:name="com.demo.service.MyService" >
...
</service>
现在我们通过继承Service
的方式定义了我们自己的MyService
类,并且在manifest
中声明了我们的MyService
,接下来我们应该启动我们自己的服务。
启动Service
第一种方式:我们是通过一个Intent
对象,并调用startService()
方法来启动MyService
。
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
注意:假如我们是通过点击Button
执行上面的代码,那么第一次点击的时候回执行其中的onCreate()
跟onStartCommand()
方法,但是当我们第二次点击的时候就只会执行onStartCommand()
方法。
为什么会这样呢? 这是由于onCreate()
方法只会在Service
第一次被创建的时候调用,如果当前Service
已经被创建过了(第一次点击创建了MyService
),不管怎样调用startService()
方法,onCreate()
方法都不会再执行。
第二种方式:通过bindService
启动Service
。
bindService
启动服务特点: 1.bindService
启动的服务和调用者之间是典型的client-server
模式。调用者是client
,service
则是server
端。service
只有一个,但绑定到service
上面的client
可以有一个或很多个。这里所提到的client
指的是组件,比如某个Activity
。
2.client
可以通过IBinder
接口获取Service
实例,从而实现在client
端直接调用Service
中的方法以实现灵活交互,这在通过startService()
方法启动中是无法实现的。
3.bindService
启动服务的生命周期与其绑定的client
息息相关。当client
销毁时,client
会自动与Service
解除绑定(client
会有ServiceConnectionLeaked
异常,但程序不会崩溃)。当然,client
也可以明确调用Context
的unbindService()
方法与Service
解除绑定。当没有任何client
与Service
绑定时,Service
会自行销毁。
启动了之后,当我们想停止服务的时候该怎么做呢?
停止Service
第一种方式:我们也是通过一个Intent
对象,并调用stopService()
方法来停止MyService
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
第二种方式:调用unbindService(conn)
方法来停止MyService
unbindService(ServiceConnection conn)
Service和Activity通信
在上面我们高高兴兴的启动了Service
了,但是细心的你可能发现了,貌似我们仅仅只是启动了而已,Activity
跟Service
并没有多少"交流",下面我们就让Activity
跟Service
交流一下。
public class MyService extends Service {
?
public static final String TAG = "MyService";
?
private MyBinder mBinder = new MyBinder();
?
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
}
?
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() executed");
return super.onStartCommand(intent, flags, startId);
}
?
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() executed");
}
?
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
?
class MyBinder extends Binder {
?
public void startDownload() {
Log.d("TAG", "startDownload() executed");
// 执行具体的下载任务
}
?
}
?
}
接下来我们在MainActivity
中通过Button
来绑定Service
和解除绑定
public class MainActivity extends Activity implements OnClickListener {
private Button bindService;
?
private Button unbindService;
?
private MyService.MyBinder myBinder;
?
private ServiceConnection connection = new ServiceConnection() {
?
@Override
public void on