IntentService
2016-01-07 14:19
447 查看
IntentService
IntentService是Service的一个子类,在收到开始请求时会立马开启一个工作线程。如果你的Service不需要同时处理多请求,那么你可以选择使用它。你需要实现onHandleIntent()方法,当它收到开始请求时,它就会在后台开始工作。
IntentService好处
1.创建一个默认的工作线程处理所有的Intent传递给onStartCommon()方法,与应用的主线程分离。
2.创建一个工作队列,每次传递一个Intent给你的onHandleIntent()实现方法。这样当你有多个运行的线程时不会混乱。
3.当所有的请求处理完时它会自己停止,不需要调用stopSelf();
4.提供默认的onBind()实现方法,返回null;
5.提供默认的onStartCommon方法,它会发送Intent到工作队列,然后再将Intent传递给你实现的onHandlerIntent方法。
简单例子
public
class HelloIntentService
extends IntentService
{
public HelloIntentService()
{
super("HelloIntentService");
}
@Override
protected voidonHandleIntent(Intent intent)
{
// Normally we would do some work here, likedownload a file.
// For our sample, we just sleep for 5 seconds.
long endTime
= System.currentTimeMillis()
+ 5*1000;
while (System.currentTimeMillis()
< endTime)
{
synchronized
(this)
{
try
{
wait(endTime
- System.currentTimeMillis());
} catch
(Exception e)
{
}
}
}
}
}
IntentService是Service的一个子类,在收到开始请求时会立马开启一个工作线程。如果你的Service不需要同时处理多请求,那么你可以选择使用它。你需要实现onHandleIntent()方法,当它收到开始请求时,它就会在后台开始工作。
IntentService好处
1.创建一个默认的工作线程处理所有的Intent传递给onStartCommon()方法,与应用的主线程分离。
2.创建一个工作队列,每次传递一个Intent给你的onHandleIntent()实现方法。这样当你有多个运行的线程时不会混乱。
3.当所有的请求处理完时它会自己停止,不需要调用stopSelf();
4.提供默认的onBind()实现方法,返回null;
5.提供默认的onStartCommon方法,它会发送Intent到工作队列,然后再将Intent传递给你实现的onHandlerIntent方法。
简单例子
public
class HelloIntentService
extends IntentService
{
public HelloIntentService()
{
super("HelloIntentService");
}
@Override
protected voidonHandleIntent(Intent intent)
{
// Normally we would do some work here, likedownload a file.
// For our sample, we just sleep for 5 seconds.
long endTime
= System.currentTimeMillis()
+ 5*1000;
while (System.currentTimeMillis()
< endTime)
{
synchronized
(this)
{
try
{
wait(endTime
- System.currentTimeMillis());
} catch
(Exception e)
{
}
}
}
}
}
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析