本节学习IntentService, 可能就有人问了, 什么是IntentService, IntentService有什么作用? 不是已经有了Service,那为什么还要引入IntentService呢?
带着这两个问题,,我们先来看一个例子:
我们新建一个MyIntentService例子:
public class MyIntentService extends IntentService {private int count = 5;public MyIntentService() {super("MyIntentService");// TODO Auto-generated constructor stub}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubLog.i("MyIntentService", "onBind————");return super.onBind(intent);}@Overridepublic void onCreate() {// TODO Auto-generated method stubLog.i("MyIntentService", "onCreate————");super.onCreate();}@Overridepublic void onDestroy() {// TODO Auto-generated method stubLog.i("MyIntentService", "onDestroy————");super.onDestroy();}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubLog.i("MyIntentService", "onStart————");super.onStart(intent, startId);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.i("MyIntentService", "onStartCommand————");return super.onStartCommand(intent, flags, startId);}@Overrideprotected void onHandleIntent(Intent arg0) {// TODO Auto-generated method stubwhile(count > 0){//设置时间的输出方式SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String time = format.format(new Date());//显示时间Log.i("MyService", time);try {//延迟一秒Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}count–;}}}其中IntentService是Service的子类,需要继承与Service。
在MyActivity中增加一个button,用于启动MyIntentService
btn_intent.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// 启动服务Intent intent = new Intent(MyActivity.this, MyIntentService.class);Log.i("MyActivity", "启动Intent服务按钮被按下!");startService(intent);}});运行效果如下:
可以看到我们的界面没有出现卡住,(关于卡住不动,请看我Service二那节)。同时打印5次后,自动destory。
既然现象已经看了,我总结一下:
Service与IntentService之间的区别
在这之前,需要知道Service的不足之处
a: Service不是专门的一条新的线程,因此不应该在Service中处理相当耗时的任务
b:service也不会专门的启动一个新的线程,Service与它所在的应用位于同一个进程中的。
所以,对于Service的2个缺陷,就引入了IntentService。
a:IntentService会使用一个队列来关联Intent的请求,每当Activity请求启动IntentService时,IntentService会将该请求加入一个队列,然后开启一个新的线程去处理请求。所以IntentService不会把主线程卡死
b:IntentService会创建单独的线程处理onHandleIntent()方法里的实现代码
c:同时IntentService不用重写onBind, OnStartCommand方法,只需实现onHandleIntent()方法
d:当所以的请求处理完后,Intent后自动停止服务,无需手动停止服务
版权声明:本文为博主原创文章,未经博主允许不得转载。
有希望在的地方,痛苦也成欢乐