Android Service 開發注意事項

吐槽一下

    看過不少關於Android Service開發的文章, 而其中大部分在講解遠程服務時, 都只是照搬了代碼格式, 即使是使用了AIDL (Android Interface Definition Language), 也用了IBinder接口, 可是App在實際運行中仍是以本地服務的方式啓動的. html

除此以外, 在調試時, 咱們還能夠看到 ServiceConnection::onServiceConnected(ComponentName name, IBinder binder) 中binder的實際類型, 經過該類型, 便可知App到底調用的是本地對象仍是遠程對象. android

P.S. IBinder是Android RPC (Remote Procedure Call) 的核心接口, 其中Camera, MediaPlayer等都是經過RPC技術實現的, 而爲之服務的就是一個獨立的進程, 這個能夠經過adb shell ps 能夠看到. shell

具體請參考 Android 源碼 http://source.android.com/ . app


進入正題

本地/遠程服務最大的區別在於對 AndroidManifest.xml中service屬性 android:process 的設置, 而該屬性是能夠隨意設置的, 好比 android:process=":remote_1". ide

該屬性一旦設置, 那麼App啓動以後, Service確定會以遠程服務方式啓動, ---- 可經過adb shell ps 就能夠看到有一個獨立的進程啓動了.  ui

假設項目 Package爲 net.oschina.demo , 並設置 android:process=":remote_1", 那麼App運行時, 經過 adb shell ps | grep net.oschina.demo , 能夠看到有兩個進程: spa

  • net.oschina.demo
  • net.oschina.demo:remote_1


官方文檔

http://developer.android.com/guide/components/services.html
http://developer.android.com/reference/android/app/Service.html
相關文章
相關標籤/搜索