服務(Service)是Android四大元件之一,主要用于背景運作和跨服務程序通路。Service并沒有UI部分,而是一直在Android系統的背景運作。應用程式一般使用service做一些背景運作的工作,例如,下載下傳檔案。
Service也是有生命周期的,但Service的生命周期很簡單,隻有3個階段:
建立服務;
開始服務;
銷毀服務;
一個服務隻會建立一次,銷毀一次,但可以開始多次
public class MyService extends Service{
@Override
public IBinder onBind(Intent intent) {
return null;
}
//當服務第一次建立時調用
@Override
public void onCreate() {
Log.d("MyService","onCreate");
super.onCreate();
}
//當服務銷毀時調用
@Override
public void onDestroy() {
Log.d("MyService","onDestroy");
super.onDestroy();
}
//開始服務是調用
@Override
public void onStart(Intent intent, int startId) {
Log.d("MyService","onStart");
super.onStart(intent, startId);
}
}
Service也需要去AndroidManifest.xml檔案中配置
android:enabled屬性的值為true,表示MyService服務處于激活狀态。雖然是激活的但是系統不會啟動,想要啟動必須顯示地調用startService。停止也是一樣stopService。
當然我們可以弄開機啟動Service,類似Broadcast Receiver(我上一篇部落格有講)。
public class StartupReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context,MyService.class);
//啟動Service
context.startService(serviceIntent);
Log.d("start_service","OK!");
}
}
配置檔案
<uses-permission android:name="ANDROID.PERMISSION.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"/>
<receiver android:name=".StartupReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
運作,然後重新開機模拟器,看看LogCat試圖中是否輸出了相應的日志資訊。