1、什麼是Service
2、服務類型
3、本地服務的生命週期
兩種服務的特點:
4、服務啓動
4.1、Start啓動
首先我們需要一個類繼承自Service,並且根據服務的生命週期我們需要複寫他的方法代碼如下:
package com.example.liujing.servicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by liujing on 16/2/1.
*/
public class MyStartService extends Service {
@Override//啓動服務是調用此方法
public void onCreate() {
super.onCreate();
Log.d("infoservice","onCreat");
}
@Override//銷燬服務是調用此方法
public void onDestroy() {
super.onDestroy();
Log.d("infoservice", "onDestroy");
}
@Override//調用服務方法
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("infoservice", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
然後我們需要在AndroidManifest對服務進行聲明:
<service android:name=".MyStartService"/>
最後回到主線程中啓動和停止服務代碼如下: