您的位置:首页 > 移动开发 > Android开发

Android学习六之Service(二)

2011-10-09 08:30 281 查看
昨天晚上实在是不方便,写到一半没法写下去了,今天早上到一卡通再充了一下电卡,终于有电了!

闲话少说,把Service接下来的部分写完。

上次写到当我们的service需要处理多线程的时候,我们需要从Service这个基类进行扩展,具体步骤通过文档里的代码来说明:

public class HelloService extends Service {
	private Looper mServiceLoopr;
	private ServiceHandler mServiceHandle;

	private class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			long endTime = System.currentTimeMillis() + 5 * 1000;
			while (System.currentTimeMillis() < endTime) {
				synchronized (this) {
					try {
						wait(endTime - System.currentTimeMillis());
					} catch (Exception e) {

					}
				}
			}
			// Stop Service
			stopSelf(msg.arg1);
		}

	}

	@Override
	public void onCreate() {
		// Start up the thread running the service. Note that we create a
		// separate thread because the service normally runs in the process's
		// main thread, which we don't want to block. We also make it
		// background priority so CPU-intensive work will not disrupt our UI.

		HandlerThread handlerThread = new HandlerThread("Service Start Arguments", Process.THREAD_PRIORITY_BACKGROUND);
		handlerThread.start();
		
		mServiceLoopr = handlerThread.getLooper();
		mServiceHandle = new ServiceHandler(mServiceLoopr);
		
	}

	@Override
	public void onDestroy() {
		Toast.makeText(this, "Service Done", Toast.LENGTH_SHORT).show();
		
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Toast.makeText(this, "Service Starting", Toast.LENGTH_SHORT).show();
		
		Message msg = mServiceHandle.obtainMessage();
		msg.arg1 = startId;
		
		mServiceHandle.sendMessage(msg);
		
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}


在onStartCommand()方法中,需要返回一int值,文档里给出了三个值:



个人觉得更好的一种方法是这样看:

在Eclipse中,



我相信只要花一些时间看,这些英文还是能看得懂的

START_NOT_STICKY:系统在调用onStartCommand()方法后杀死了这个Service,不再从新启动Service,除非有另外的Intent驱动他启动,这种是最安全的做法。
 
START_STICKY:系统在调用onStartCommand()方法后杀死了这个Service,会重新创建一个Service,创建的Service是会以一个为空的 intent作为参数传给onStartCommand(),如果此时有其他的intent启动了Service,在这种情况下,这些intent都会被传递给onStartCommand(),这种情况很适合用于播放。
 
START_REDELIVER_INTENT:系统在调用onStartCommand()方法后杀死了这个Service,会以最后一个intent作为参数传给onStartCommand(),重新启动Service。这种情况很适合做下载的服务。



启动Service

Intent intent = new Intent(this, HelloService.class);
startService(intent);


停止Service

Service停止有两个方法:

1,在自己的生命周期里调用
stopSelf()


[code]2,其他组件调用
stopService()


[code]
 

[code]
管理Service的生命周期


[code]
 

[code]
Service的生命周期有两种:


[code]
The entire lifetime :整个的生命周期


[code]
The active lifetime :活跃的生命周期






本来是想再看一下这个Bound Service的,但昨天晚上定错了闹钟,不到7点就起来,精力有些不够了,而且看到文档里专门拿出一页来说这个Bound Service,所以还是下次再说吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: