Android Service---继承IntentService类
来源:互联网 发布:api接口怎么用java 编辑:程序博客网 时间:2024/04/29 13:55
IntentService类执行以下操作:
1. 创建一个独立与应用程序主线程的默认工作线程,执行所有的给onStartCommand()方法Intent的处理;
2. 创建一个工作队列,以便每次只给你的onHandleIntent()方法实现传递一个Intent,因此你不必担心多线程的问题;
3. 所有的启动请求都被处理之后终止这个服务,因此你不需要自己去调用stopSelf()方法;
4. 提供返回null的onBind()方法的默认实现;
5. 提供一个给工作队列发送Intent对象的onStartCommand()方法的默认实现和onHandleIntent()方法的实现。
所以这些加起来实际上只需要实现onHandleIntent()方法,来完成由客户提供的工作(虽然,你还需要给服务提供一个小的构造器)。
例如:
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download 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) {
}
}
}
}
}
以上就是你做的全部:一个构造器和一个onHandleIntent()方法的实现。
如果你还决定要重写其他的回调方法,如onCreate()、onStartCommand()、或onDestroy(),那么就要确保调用父类的实现,以便IntentService对象能够适当的处理工作线程的活动。
例如,onStartCommand()方法必须返回默认的实现(默认的实现获取Intent并把它交付给onHandleIntent()方法):
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent,flags,startId);
}
除了onHandleIntent()方法以外,唯一不需要调用实现的方法是onBind()方法(但是如果你的服务允许绑定,就要实现这个方法)。
- Android Service---继承IntentService类
- Android Service---继承IntentService类
- android service 继承IntentService和Service
- android Service和IntentService
- Android Service 与 IntentService
- 62 Android Service IntentService
- Android IntentService vs Service
- Android Service---继承Service类
- Android Service---继承Service类
- 继承service和IntentService有什么区别?
- android service 之二(IntentService)
- Android 中Service 和IntentService
- android service 之二(IntentService)
- android之Service(2)IntentService
- Android---43---Service之IntentService
- android中service之intentService
- Android中的Service(IntentService)
- android service 之二(IntentService)
- JVM 深入笔记(1)内存区域是如何划分的
- 重寻斗志
- 交叉编译opencv
- C语言和设计模式(总结篇)
- 并行博弈树搜索算法-第4篇 更上一层楼:Alpha-Beta算法的改进
- Android Service---继承IntentService类
- 浅谈对C语言指针的理解
- 《诗意的边缘》相关代码下载
- Java知识
- 各大IT公司2012校园招聘笔试面试整理
- submit assembly to NCBI
- Leaveing a voicemail message
- UITableViewCell - UITableView中cell的边框和背景
- pdflatex 插入 EPS 格式图片的两种方法