Service-IntentService集成异步线程(2)
来源:互联网 发布:ubuntu wine命令 安装 编辑:程序博客网 时间:2024/06/05 15:39
执行耗时操作的服务对界面会阻塞界面的操作。新开的线程在服务关闭后还会执行,造成了
代码复杂。系统提供了IntentService来解决这个问题,即耗时操作只需要放在该类的onHandleIntent()中即可;
1.继承IntentService:
/** * @author linwb */public class LeanIntentService extends IntentService {public LeanIntentService(){super("");}@Overridepublic void onCreate() {super.onCreate();Log.v("LeanLog", "onCreate PID= "+Process.myTid());}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.v("LeanLog", "onStartCommand PID= "+Process.myTid());return super.onStartCommand(intent, flags, startId);}@Overrideprotected void onHandleIntent(Intent arg0) {Log.v("LeanLog", "onHandleIntent PID= "+Process.myTid());}}
2.在xml文件中配置
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <service android:name=".LeanIntentService"></service> <activity android:name="com.csz.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
3.调用startService(Intent);
Intent mServiceIntent=new Intent(MainActivity.this,LeanIntentService.class);startService(mServiceIntent);
运行如下:
分析如下:
IntentService启动调用onCreate();该方法创建了一个HandlerThread;
执行onStartCommand()时,从线程队列中取出一条线程,并向线程发送消息,
在HandlerThread中的线程获取消息后,执行onHandleIntent。执行完后关闭Service,如下:
但总的来说。用户只需要在onStartCommand()中新开一条线程执行任务或者在
onHandleIntent()中执行耗时操作即可。
0 0
- Service-IntentService集成异步线程(2)
- Service的异步版本IntentService:
- Service学习——第五篇 使用IntentService在单独线程上执行异步任务
- Service IntentService Android中的线程 MediaPlayer
- Android Service跟线程及IntentService使用
- android之Service(2)IntentService
- Service、IntentService
- Service和IntentService的区别2
- 01.2异步服务IntentService
- Service和IntentService
- android Service和IntentService
- 关于IntentService和Service
- Android Service 与 IntentService
- Service与IntentService
- Service 和 IntentService
- IntentService和Service比较
- 62 Android Service IntentService
- Service和IntentService
- Oracle第一讲
- 如何访问code.google.com
- poj 2003 Hire and Fire list+hash+模拟
- PaaS平台– Google App Engine的开源实现AppScale环境搭建
- CentOS 6.5 ZIP、RAR文件压缩解压操作详解
- Service-IntentService集成异步线程(2)
- TOJ 1701: Face The Right Way
- 把Session放入到Memcachad中的配置
- uva 10487 Closest Sums (遍历&二分查找&&双向查找)
- CKEditor图片上传实现详细步骤(使用Struts 2)
- 简述易语言与API
- C++类的编译过程
- jquery使用经验总结
- 模拟服务器