Service 是android四大组件之一,它也有自己的生命周期,创建、配置service创建、配置Activity 的过程基本相似。
Service没有前台程,只是在后台运行。
开发步骤,
- 定义一个继承Service的子类
- 在AndoirdManifest.xml 文件中配置该Service
介绍一下Service子类中常用的方法。
- abstract IBinder onBinder(Intent intent);该方法是Service 子类必须实现的方法,该方法返回一个IBinder对象,应用程序可以通该该对象与Service组件通信。
- void onCreate(); 当该Service第一次被创建后将立即回调该方法。
- void destroy(); 当该Service 被关闭之前将会回调该方法。
- void onStartCommand(Intent intent,int flags,int startId);该方法的早期版本是onStart(Intnet intent,int startId) 第次客户端调用startService(Intent) 方法启动该方法的Service 时都会回调该方法。
- boolean onUnbind(Intent intent);当该Service上绑定的所有客户端都断开连接时将会回调该方法。
以下为代码实现。
第一步:我们写一个FirstService 实现自Service
package com.hkrt.action;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class FirstService extends Service {
@Override
public IBinder onBind(Intent intent) {
System.out.println("onBind");
return null;
}
//此service被创建时调用
@Override
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
}
//此service被启动时回调此方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
return START_STICKY;
}
//此service被关闭这前回调
@Override
public void onDestroy() {
System.out.println("onDestroy");
super.onDestroy();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hkrt.action"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ServiceDemoActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirstService">
<intent-filter >
<action android:name="com.hkrt.action.FIRST_SERVICE"/>
</intent-filter>
</service>
</application>
</manifest>
第三步:我们要通过两个Button 来开启和停止这个Service.代码比较简单就不写了。

第四步:代码开启和停止这个Service.
package com.hkrt.action;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ServiceDemoActivity extends Activity {
Button start,end;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.startService);
end = (Button)findViewById(R.id.stopService);
final Intent intent = new Intent();
intent.setAction("com.hkrt.action.FIRST_SERVICE");
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(intent);
}
});
end.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(intent);
}
});
}
}
开启时:图片

结束时:图片
Service 的生命周期