由上面的生命周期图可以看出,它的生命周期只有三个阶段:onCreate、onStartCommand、onDestroy。
需要注意的有:
1. 如果是调用者直接退出而没有调用stopService的话,那么被启动的Service会一直在后台运行,直至它的stopService方法被调用,或者它自己调用stopSelf方法。
2. 在服务未被创建时,系统会先调用服务的onCreate方法,接着调用onStartCommand方法。如果调用startService方法前服务已经被创建,那么会再次调用onStartCommand方法。并且,不管调用了多少次onStartCommand方法,只需要一次stop便可以将相应的service关闭。
3. 具体的操作是在onStartCommand方法中执行的。
为了便于理解,我们创建一个工程,命名为ServiceINS:
package com.example.serviceins;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* startService: 服务在同一时间只会被创建一次,可以通过外部调用stopService或自身调用stopSelf来终止服务
*
* 当执行一个已启动的服务,会直接调用onStartCommand方法来执行任务
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 启动一个服务
*
* @param view
*/
public void startClick(View view) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
/**
* 停止一个服务
*
* @param view
*/
public void stopClick(View view) {
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
}
在布局中加入两个按钮:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="startClick"
android:text="启动Service" />
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="stopClick"
android:text="停止Service" />
实现一个Service:
package com.example.serviceins;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("MyService-onCreate");
}
// 在该方法中实现服务的核心业务
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
for (int i = 0; i
System.out.println("onStartCommand" + i);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("MyService-onDestroy");
}
}
android:name=".MyService"
android:enabled="true">
下面,我们通过操作来观察一下LogCat中的输出情况:
首先点击“启动Service”,如下图,先后执行了Service当中的onCreate方法和onStartCommand方法
再点击一次“启动Service”,这时,我们看到再次执行了一次onStartCommand中的方法,但并没有再次去调用onCreate方法
然后依次点击“停止Service”和“启动Service”,只调用了一次onDestroy方法就将service关闭掉了,再次开启service的时候又会重新调用onCreate和onStartCommand方法