首页 > 代码库 > 一分钟掌握Service生命周期

一分钟掌握Service生命周期

Service有两种启动方式,1、通过startService启动。2、通过bindService()方式启动。下图说明了以两种方式启动时service的生命周期。

                                                                                 


写个例子说明

一、Service

package com.example.aidlexample;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import com.example.aidlexample.Dog.Stub;

public class DogDescribe extends Service {

	// 通过startService()方式调用
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		System.out.println("通过startService方式调用" + "onStartCommand()执行 ");
		return super.onStartCommand(intent, flags, startId);
	}

	private DogBinder dogbinder;

	// 将IBinder对象返回给访问者
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("通过bindService调用" + "onBind()执行");
		return dogbinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("onUnbind()");
		return super.onUnbind(intent);
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		dogbinder = new DogBinder();
	}

	// 继承自动代码生成的类Stub(实现了IBinder接口)
	public class DogBinder extends Stub {

		@Override
		public String getDogName() throws RemoteException {
			// TODO Auto-generated method stub
			return "xiaokeai";
		}

		@Override
		public String getDogWeight() throws RemoteException {
			// TODO Auto-generated method stub
			return "30kg";
		}

	}

}

二、startService()方式启动

该方式Service里的onStartCommand()方法执行

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Intent it = new Intent();
		ComponentName comp = new ComponentName(MainActivity.this,
				DogDescribe.class);
		it.setComponent(comp);
		startService(it);
	}
执行结果:


三、bindService()方式启动

该方式Service里的onBind()方法执行,客户端调用unbindService()时,Service里的unBind()执行

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Intent it = new Intent();
		ComponentName comp = new ComponentName(MainActivity.this,
				DogDescribe.class);
		it.setComponent(comp);
		bindService(it, conn, Service.BIND_AUTO_CREATE);
	}
执行结果:



不知道大家清楚了没有,关键是看清最上面一副图,哈哈...................

一分钟掌握Service生命周期