Android基础-Service

Service也是我们经常用的组件,跟Activity不同的是,Service不会直接与用户进行交互,而是在后台做事

Service

Service的启动方式

服务的启动方式有如下两种

  • 其他的组件通过调用Context.startService()来启动服务

    1. 被启动的服务依旧在主线程中工作
    2. 即使启动服务的组件销毁,服务依然能正常工作,直至工作结束,才会被销毁
    3. 服务启动后,不会返回结构给启动服务的组件
  • 组件通过Context.bindService()与服务建立联系,并启动服务

    1. 一旦服务与组件之间没有了联系,服务会销毁
    2. 这种方式下,服务可与组件进行交互
Context.startService()

该启动方式需要重写如下方法

 public class YourService extends Service {
    public YourService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestory(){
        super.onDestory();
  }

startService()后,按照服务的生命周期,此时会回调onCreate()
但是创建Service之后再次调用startService()就不会回调onCreate()
因为服务已经存在,故回调的是onStartCommand
直至调用stopService或者stopSelf(),服务回调onDestory(),然后销毁

效果拔群

Context.bindService()
上面说到这种方式启动服务是可与组件进行交互的,它是通过Binder进行操作
我们在Binder中进行打印,代码如下

class FirstBinder extends Binder {
        void log() {
            Log.d(TAG, "-->log ");
        }
    }

然后在Service中重写onBind()

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return new FirstBinder();
    }

随后就可以在Activity中进行服务的绑定了

    //...其他代码...
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ((FirstService.FirstBinder) service).log();
        }

        @Override
         public void onServiceDisconnected(ComponentName name) {
             //托管服务的进程崩溃或被终止时回调该方法
             Log.d("tag", "onServiceDisconnected: ");
         }
    };

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, FirstService.class);
        switch (v.getId()) {
            case R.id.btn_bind:
                bindService(intent, connection, BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind:
                unbindService(connection);
                break;
            default:
                break;
        }
    }

在上述代码中,我们知道了通过ServiceConnection进行交互工作
bindService后,onServiceConnected随即调用,我们便可以在其中进行一些操作
比如拿到我们的Binder,对View的内容进行更新等

调用 Binder进行打印

image.png

其生命周期也显而易见了,bindService后就会回调onCreate->onbind->ServiceConnection中onServiceConnected的操作
但是多次调用bindService不会跟startService一样,这里指不会重复回调onbind,onServiceConnected
销毁的时候回调onUnbind->onDestory

两种方式的混合使用

Context.startService()和Context.bindService()是可以一起使用的
但是要销毁该服务的话,必须要调用unBind()和stopService()

Tips:只运行bindService后,在正在运行的服务一栏中找不到该服务

服务和线程的区别

  1. 首先服务是四大组件之一,是和Activity同一级别的
  2. 服务是运行在主线程之中的,而线程不是
  3. 服务在主线程挂掉后,服务也挂了,线程可以独立运行,直至运行结束

在工作线程中使用Service

前面说到的Service都是工作在主线程中的,为了避免出现ANR的情况,就得开辟工作线程,这时候IntentService就派上用场了

IntentService需要重写的方法

  • onHandleIntent
    此方法工作于工作线程中,线程结束后会回调onDestory

你可能感兴趣的:(Android基础-Service)