服務的基本要點:
1.後臺服務
2.無交互界面,不跟隨界面的生命週期
3.比不可見界面的優先級要高,服務經常用於播放音視頻的場合。
4.默認情況下,服務和主線程在同一個程序下運行。
一般使用異步處理後臺的大量資源計算任務。
要使用服務,一般是在service裏創建一個新的線程在後臺進行處理,然後處理完畢的時候停止服務。
運行在程序進程中的服務,稱爲本地服務。
自定義服務:
1.服務需要在AndroidManifest.xml中進行聲明,並且服務的實現類需要繼承自Service類或者他的子類
<service
android:name="MyService"
android:icon="@drawable/icon"
android:label="@string/service_name"
>
</service>
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
具體代碼:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".LocalWordService"
android:label= "Word service"/>
</application>
2.啓動服務
服務,消息接收器,活動頁面這三類組件都可以通過執行startService(intent)方法來啓動服務。
// use this to start and trigger a service
Intent i= new Intent(context, MyService.class);
// potentially add data to the intent
i.putExtra("KEY1", "Value to be used by the service");
context.startService(i);
3.執行服務
執行startService之後,服務實際上還沒有運行的,這時候服務對象被創建了,onCreat()方法被調用。
服務啓動的時候,onStartCommand(intent)被調用,此方法因爲是在主界面線程中調用,所以無需做同步處理。
無論你調用startService多少次,服務也只是啓動一次。
4.結束服務
結束服務使用stopService(),服務本身也可以調用stopSelf()來結束自己。
5.IntentServices,一次性服務
執行一次性任務的時候可以用一次性服務,例如下載任務,任務執行完後,它會自動結束自己。
6.和服務進行通信
活動界面和服務的通信有如下方式:
1.使用Intent數據
2.使用消息接收器
7.活動界面綁定到本地服務
服務在活動界面的主進程中啓動,活動界面可以直接綁定服務。
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
LocalWordService.MyBinder b = (LocalWordService.MyBinder) binder;
s = b.getService();
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
}
具體案例代碼如下:
TestLocalService.zip:
testService.zip: