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"/>
最后回到主线程中启动和停止服务代码如下: