Service和BroadcastReceiver總結

Service
1、service的隱式啓動和顯示啓動( 如果在同一個包中。兩者都可以用。在不同包時。只能用隱式啓動)
    隱式啓動
        <service android:name=".service">
            <intent-filer>
                <action android:name="com.android.service"/>
            <intent-filer>
        </service>
        final Intent serviceIntent=new Intent();
        serviceIntent.setAction("com.android.service");
    顯示啓動
        final Intent serviceIntent=new Intent(this,service.class);
        startService(serviceIntent);
2、activity對service的調用:startService()和bindService()
     兩者生命週期的區別

     1)startService()方法
      這種service可以無限地運行下去,必須調用stopSelf()方法或者其他組件調用stopService()方法來停止它。 當service被停止時,系統會銷燬它。多次調用startService(),只會調用1次onCreate(),但會多次調用onStartCommand()方法。
     2)bindService()方法
        客戶可以通過一個IBinder接口和service進行通信。 客戶可以通過 unbindService()方法來關閉這種連接。一個service可以同時和多個客戶綁定,當多個客戶都解除綁定之後,系統會銷燬service。
         IBinder對象相當於Service組件中的內部鉤子,可以訪問Service內部數據,Activity通過IBinder類和Service通信。在實際開發中,通常在Service中定義一個Binder的子類。
         bindService(Intent service, ServiceConnection conn, int flags),啓動Service。ServiceConnection類,用於監聽訪問者和Service之間的鏈接情況。當activity和service鏈接成功後回調ServiceConnection對象的onServiceConnected方法,可在該方法中獲取IBinder對象。
        多次調用 bindService(),只會調用1次onCreate()和onBind()方法。
3)IntentService的使用
      Service不是一條新線程,不應該在其中處理耗時任務。Service不會啓動一個單獨的線程,它與所在應用處於同一個進程中。
     intentservice是Service的子類,只需要實現onHandleIntent()方法

BroadcastReceiver
BroadcastReceiver是一個系統級的全局監聽器,能夠實現不同組件之間的通信。在實現BroadcastReceiver時,主要實現其中的onReceiver()方法,但是不能執行耗時操作。
1、使用步奏
       1)註冊BroadcastReceiver,代碼註冊或者xml註冊
       2)創建Intent,用於啓動BroadCastReceiver
       3)調用指定BroadcastReceiver:Context的sendBroadcast()或者sendOrderedBroadcast
2、註冊
      1)代碼註冊(適合將BroadcastReceiver作爲內部類使用)
         IntentFilter filter=new IntentFilter("android.provider.xxx");//intent過濾器
         MyReceiver receiver=new MyReveiver();//Receiver對象
         registerReceiver(receiver,filter);//註冊//unregisterReceiver(receiver);//取消註冊
      2)AndroidManifest.xml註冊(適合將BroadcastReceiver單獨的類)
       <intent-filter>
                <action android:name="com.simware.BroadcastReceiverDemo" >
                </action>
      </intent-filter>  
3、普通廣播和有序廣播
     1)普通廣播(Normal Broadcast):系統異步發送廣播,同一時刻可以被所有接受者受到,效率高,但接受者不能將處理結果傳遞給下一個接受者。通過Context的sendBroadcast()發送普通廣播
     2)有序廣播(Ordered Broadcast):接受者將按照實現規定的優先級依次接收Broadcast。接收者可以終止Broadcast Intent的傳播,低優先級的接收者將不會受到廣播。同時接受者可以將數據傳遞給下一個接受者:setResultExtras(Bundle)來存放數據和getResultExtras(true)來接收上級廣播的數據;通過Context的sendOrderedBroadcast()發送普通廣播
       <intent-filter android:priority="20">
                <action android:name="com.simware.BroadcastReceiverDemo" >
                </action>
      </intent-filter>  

Service和Activity的通信方式
1、bindService()啓動service,通過內部鉤子IBinder對象實現兩者的溝通
2、startService()啓動service,藉助BroadcastReceiver來實現數據通信,此時最好將Receiver定義爲Activity的內部類,這樣Receiver可以直接操控activity的數據。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章