服务(service)是Android的四大组建之一。它主要用于在后台处理一些耗时的逻辑,或者去执行某些需要长期运行的任务。必要的时候我们甚至可以在程序退出的情况下,让Service在后台继续保持运行状态。
使用Android的service通常有两种方式:1、startService;2、bindService
新建一个MyService继承Service,需要在项目的配置文件AndroidManifest.xml注册该服务,如果使用AndroidStudio添加服务会自动在配置文件注册该服务。启动服务离不开Intent,我们需要通过新建一个intent对象指向需要用到的服务。
1、startService:相当于发一个指令,然后服务启动,按照之前定好的程序运行,做自己的工作,与activity互不干涉,就像开环控制一样。在服务里添加stopSelf()可以随时关闭本身服务,或者调用stopService();
- 启动:
- Intent startIntent = new Intent(this, MyService.class);
- startService(startIntent);
- 停止:
- Intent stopIntent= new Intent(this, MyService.class);
- stopService(stopIntent);
-
2、bindService:Activity与service建立起关联的启动服务。
需要使用MyService中的onBind与activity建立起关联。新建内部类 MyBinder extends Binder ,在MyBinder内可添加方法,比如下载调用,创建MyBinder实例, MyBindermBinder = MyBinder(); 在onBind中返回给activity:
- @Override
- public IBinder onBind(Intent intent) {
- return mBinder;
- }
- private MyService.MyBinder myBinder;
- private ServiceConnection connection = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- myBinder = (MyService.MyBinder) service; //向下转型得到MyBinder实例
- myBinder.startDownload();
- }
- };
- 绑定服务:
- Intent bindIntent = new Intent(this, MyService.class);
- bindService(bindIntent, connection, BIND_AUTO_CREATE);
- 解绑服务:
- unbindService(connection);
bindService()方法接收三个参数,第一个参数就是刚刚构建出的Intent对象,第二个参数是前面创建出的ServiceConnection的实例,第三个参数是一个标志位,这里传入BIND_AUTO_CREATE表示在Activity和Service建立关联后自动创建Service,这会使得MyService中的onCreate()方法得到执行,但onStartCommand()方法不会执行。