Service

作者: 果果人8023 | 来源:发表于2018-03-23 17:11 被阅读0次

    生命周期

    image

    1、简介

    服务存在两种,
    一种事本地服务Local Service,本地服务用于应用程序内部
    一种是远程服务Remote Service,用于android 系统内部的应用程序之间

    2、本地服务

    本地服务通常有两种启动方式: start 启动方式  和 bind启动方式
    

    a、start启动方式

    1,onCreate() 创建服务,多次创建方法只运行一次
    2,onStartCommand() start一次执行一次
    3,onDestroy() 外部调用了stopService或者stopSelf 时执行

    • Service代码

      /**
       * start启动
       */
      
      public class LocalService extends Service {
      
        @Override
        public void onCreate() {
            Log.i("Kathy", "onCreate - Thread ID = " + Thread.currentThread().getId());
            super.onCreate();
        }
      
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("Kathy", "onStartCommand - startId = " + startId + ", Thread ID = " + Thread.currentThread().getId());
            return super.onStartCommand(intent, flags, startId);
        }
      
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            Log.i("Kathy", "onBind - Thread ID = " + Thread.currentThread().getId());
            return null;
        }
      
        @Override
        public void onDestroy() {
            Log.i("Kathy", "onDestroy - Thread ID = " + Thread.currentThread().getId());
            super.onDestroy();
        }
      }
      
    • AndroidManifest代码

      <!--本地服务-->
      <service android:name=".local.LocalService" />
      
    • Activity代码

      //start启动方式
      Intent service = new Intent(this, LocalService.class);
      startService(service);
      

    b,bind启动方式

    1,bindService启动的服务和调用者是 client-service 模式,一个service 可以被多个client绑定,
    2,同一个界面绑定多次,onCreate、onStartCommand只会执行一次,bind方法可以执行多次
    3,当client被销毁时自动与Service解除绑定,client也可以调用unbindService与Service解除绑定,
    4,当时Service没有任何client与Service绑定的时候,自动会被销毁

    • Service代码

      /**
         * bind服务
      */
      
      public class LocalBindService extends Service {
      
        //client 可以通过Binder 获取Service
        public class LocalBinder extends Binder {
            public LocalBindService getService() {
                return LocalBindService.this;
            }
        }
      
        //Client与Service 之间通讯
        private LocalBinder localBinder = new LocalBinder();
        private final Random random = new Random();
      
        @Override
        public void onCreate() {
            Log.i("Kathy", "LocalBindService - onCreate - Thread = " + Thread.currentThread().getName());
            super.onCreate();
        }
      
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("Kathy", "LocalBindService - onStartCommand - startId = " + startId + ", Thread = " + Thread.currentThread().getName());
            return super.onStartCommand(intent, flags, startId);
        }
      
      
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            Log.i("Kathy", "LocalBindService - onBind - Thread = " + Thread.currentThread().getName());
            return localBinder;
        }
      
      
        @Override
        public boolean onUnbind(Intent intent) {
            Log.i("Kathy", "LocalBindService - onUnbind - from = " + intent.getStringExtra("from"));
            return super.onUnbind(intent);
        }
      
        @Override
        public void onDestroy() {
            Log.i("Kathy", "LocalBindService - onDestroy - Thread = " + Thread.currentThread().getName());
            super.onDestroy();
        }
      
        //getRandomNumber是Service暴露出去供client调用的公共方法
        public int getRandomNumber() {
            return random.nextInt();
        }
      }
      
    • Activity代码

      /**
         * 绑定界面
      */
      
      public class BindServiceActivity extends AppCompatActivity {
      
        private LocalBindService localBindService;
        private boolean isBind = false;
      
        private ServiceConnection serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                isBind = true;
                LocalBindService.LocalBinder localBinder = (LocalBindService.LocalBinder) iBinder;
                localBindService = localBinder.getService();
                Log.i("Kathy", "BindServiceActivity - onServiceConnected");
                int num = localBindService.getRandomNumber();
                Log.i("Kathy", "BindServiceActivity - getRandomNumber = " + num);
            }
      
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                isBind = false;
                Log.i("Kathy", "BindServiceActivity - onServiceDisconnected");
            }
        };
      
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.bind_service_main);
      
        }
      
        //绑定服务
        public void bind(View view) {
            Intent bindService = new Intent(this, LocalBindService.class);
            Log.i("Kathy", "BindServiceActivity - bind");
            bindService(bindService, serviceConnection, BIND_AUTO_CREATE);
        }
      
        //解除绑定
        public void unbind(View view) {
            Log.i("Kathy", "BindServiceActivity - unbind");
            unbindService(serviceConnection);
        }
      
        //下一个页面
        public void next(View view) {
            Intent intent = new Intent(this, BindServiceActivity.class);
            startActivity(intent);
            finish();
        }
      
        @Override
        protected void onDestroy() {
            super.onDestroy();
            Log.i("Kathy", "BindServiceActivity - onDestroy");
        }
      }
      

    2、远程服务

    远程服务也被称为独立进程,它可以用于两种情况
    1,同一个app中运行
    2,不同app中运行

    a,AIDL接口的创建

    远程服务需要通过AIDL定义的接口提供给client

    注:如果服务端与客户端不在同一App上,需要在客户端、服务端两侧都建立该aidl文件。

    Android Studio 中的新建栏目里面存在一个可以直接创建的选择


    image.png
    • IMyAidlInterface代码

      // IMyAidlInterface.aidl
      package poetry.com.service.remote;
      
      // Declare any non-default types here with import statements
      
      interface IMyAidlInterface {
          /**
           * Demonstrates some basic types that you can use as parameters
           * and return values in AIDL.
           */
          String getValue();
      }
      

    b,Service的创建

    /**
     * 远程服务
     */
    
    public class RemoteService extends Service {
    
        private final Random random = new Random();
    
        //实现接口中暴露给客户端的stub
        private IMyAidlInterface.Stub stub = new IMyAidlInterface.Stub() {
            @Override
            public String getValue() throws RemoteException {
                return getRandomNumber();
            }
        };
    
        @Override
        public void onCreate() {
            Log.i("Kathy", "RemoteService - onCreate - Thread = " + Thread.currentThread().getName());
            super.onCreate();
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("Kathy", "RemoteService - onStartCommand - startId = " + startId + ", Thread = " + Thread.currentThread().getName());
            return super.onStartCommand(intent, flags, startId);
        }
    
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            Log.i("Kathy", "RemoteService - onBind - Thread = " + Thread.currentThread().getName());
            return stub;
        }
    
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.i("Kathy", "RemoteService - onUnbind - from = " + intent.getStringExtra("from"));
            return super.onUnbind(intent);
        }
    
        @Override
        public void onDestroy() {
            Log.i("Kathy", "RemoteService - onDestroy - Thread = " + Thread.currentThread().getName());
            super.onDestroy();
        }
    
        //getRandomNumber是Service暴露出去供client调用的公共方法
        public String getRandomNumber() {
            return random.nextInt() + "";
        }
    }
    

    c,AndroidMainfest配置

    <!--远程服务-->
        <service
            android:name=".remote.RemoteService"
            android:process="com.remote">
            <intent-filter>
                <action android:name="poetry.com.service.remote.RemoteService" />
            </intent-filter>
        </service>
    

    注意:
    andorid:process属性设置
    1,私有进程以冒号‘:’为前缀,这表示新的进程名为yourPackage:remote,其他应用的组件不可以和它运行在同一进程中
    2,全局进程不以冒号‘:’为前缀,以小写字母开头,表示其他应用可以通过设置相同的ShareUID和它运行在同一个进程中

    d,Activity的使用

    /**
     * 远程服务界面
     */
    
    public class RemoteServiceActivity extends AppCompatActivity {
    
        private IMyAidlInterface iMyAidlInterface;
    
    
        private ServiceConnection serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                iMyAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
    
                Log.i("Kathy", "RemoteServiceActivity - onServiceConnected");
                String num = null;
                try {
                    num = iMyAidlInterface.getValue();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                 Log.i("Kathy", "RemoteServiceActivity - getRandomNumber = " + num);
            }
    
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.i("Kathy", "RemoteServiceActivity - onServiceDisconnected");
                // 断开连接
                iMyAidlInterface = null;
            }
        };
    
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.bind_service_main);
    
        }
    
        //绑定服务
       public void bind(View view) {
            Intent bindService = new Intent(this, RemoteService.class);
            Log.i("Kathy", "RemoteServiceActivity - bind");
            bindService(bindService, serviceConnection, BIND_AUTO_CREATE);
        }
    
        //解除绑定
        public void unbind(View view) {
            Log.i("Kathy", "RemoteServiceActivity - unbind");
            unbindService(serviceConnection);
        }
    
        //下一个页面
        public void next(View view) {
            Intent intent = new Intent(this, RemoteSecondeActivity.class);
            startActivity(intent);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            Log.i("Kathy", "RemoteServiceActivity - onDestroy");
            if (serviceConnection != null) {
                unbindService(serviceConnection);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Service

          本文链接:https://www.haomeiwen.com/subject/tkvxcftx.html