Android---------------Service的学习

一、创建与启动Servcie的三个步骤 :

  1. 创建一个类并继承Servcie

  2.在配置文件中注册服务

  3.通过Intent来启动服务  

  

二、Service的两种启动方式

  1.startServce的启动方式 : 它是通过startService的方式来启动,不会与启动源有关系。当启动源销毁后,它的Service不会被销毁

   intent = new Intent();
   intent.setClass(MainActivity.this, MyService.class);
   startService(intent);
 

  2.bind的启动方式  : 它是通过bindService的方式来启动的,会和启动源绑定有关系。当启动源销毁后,它的Service也会跟随绑定来消失

   public class MyService extends Service {


   public class MyBinder extends Binder{
    public MyService getService(){
    return MyService.this;
    }
  }

    @Override
   public IBinder onBind(Intent intent) {
    Log.i("info", "onBind: ");
    return new MyBinder();
  }

   intent1 = new Intent();
   intent1.setClass(MainActivity.this , MyService.class);
   bindService(intent1, coon, Service.BIND_AUTO_CREATE);

   /////最应该的注意事项,一定小心它的解绑的位置,应该放在Activity的销毁位置解除绑定,否则会报错

     @Override
    protected void onDestroy() {
      super.onDestroy();
      unbindService(coon);
    }

三、AIDL的使用步骤

  1.对外提供的服务,继承Binder类之外还需要抽取接口(定义规范,面向接口编程)

  2.把接口名改成AIDL,系统会自动生成相应的标准文件(把AIDL的public的访问修饰符删除),此步骤会在gen文件下生成相应的接口

  3.让对外提供的服务类class MyService extend Stub

   

原文地址:https://www.cnblogs.com/liunx1109/p/9871712.html