昨天晚上实在是不方便,写到一半没法写下去了,今天早上到一卡通再充了一下电卡,终于有电了!
闲话少说,把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()
2,其他组件调用
stopService()
管理Service的生命周期
Service的生命周期有两种:
The entire lifetime :整个的生命周期
The active lifetime :活跃的生命周期
本来是想再看一下这个Bound Service的,但昨天晚上定错了闹钟,不到7点就起来,精力有些不够了,而且看到文档里专门拿出一页来说这个Bound Service,所以还是下次再说吧