Service基本講解

一.啓動和停止方式

  1,startService() stopService()  stopself()   stopSelfResult()

    此種方式啓動的特點:服務啓動之後跟啓動源無任何關係,無法得到服務對象

  

   2,bindService()   unbindService()

    啓動特點:通過IBinder接口實例,返回一個ServiceConnection對象給啓動源,通過ServiceConnection對象的相關方法可以得到service對象


二.生命週期

1,unbounded service  :call to startService()-->onCreate()-->onStartCommand()-->Service Running-->(Service is stoped by itself or clients)-->onDestory()-->service shut down

 2.Bounded  Service:call to bindService()-->onCreate()--onBind()-->Clients are bounded to service-->(All clients unbinded by calling unbindService)-->onUnbind()--                                                          ->onDestory()--->service shut down

三.兩種方式啓動Service

Myservice1

  1,start方式:

                     Intent intent = new Intent(MainActivity.this,Myservice1.class);

                      startService(intent);

                      stopService(intent);

  2,bind方式:

                     bindService(intent,ServiceConnection對象,BIND_AUTO_CARATE);

                     unbindService(ServiceConnection對象)、

如何得到ServiceConnection對象:

2.1通過Myservice1中onBind()方法返回值IBinder接口實例

(IBinder只是一個接口,不能創建實例,Android中給我們提供的Binder類已經實現了IBinder接口,因此只需要創建內部類MyBinder來繼承Binder即可,MyBinder中的方法和參數自定,本例中我們將返回MyService1對象)

   class MyBinder extends Binder{

          public MyService1 getService(){

               return MyService1.this;

          }

       }

2.2在MyService1中onBind()方法終於派上了用場

   public IBinder onBind(Intent intent){

             return new MyBinder();

        }

2.3在Myserivce1中創建幾個模擬方法:play()  ,pause(),previous() ,next()

2.4在MainActivity中創建ServiceConnection:

        Myservice1 service;

       SerivceConnection conn = new ServiceConnection(){

        //當啓動源跟Service連接意外丟失的時候會調用這個方法,比如Service崩潰了或者被強行停止了

       onServiceDisconnected(){};

      //當啓動源跟Service連接之後會自動調用這個方法

      onServiceConnected(組件名,IBinder binder){

         //根據biner即爲生成的MyBinder對象,之後binder便可以調用MyBinder中的方法獲得MyService1實例,也是IBinder接口實例,

        service = (Myservice1)binder.getService();

        

      }

   };

//之後得到的service便可以調用MyService1中的方法了

之後更改bindService(intent,conn,BIND_AUTO_CREATE)

               unbindService(conn);

四.兩種啓動方式配合使用,可以在沒有unbind()的情況下,程序直接退出不會出現錯誤

     startService(intent)

      bindService(intent,conn,BIND_AUTO_CREATE);

     在MainActivity中的onDestory()方法中:

     stopService(intent);

      unbindService(conn)

兩種啓動方式:當服務啓動後不需要從啓動源獲取數據,可以用start啓動

                              服務啓動之後,UI不需要了,但仍需要得到回傳的數據,可以把兩種混合使用





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章