你所不知道的IntentService
来源:互联网 发布:淘宝一千零一夜在哪 编辑:程序博客网 时间:2024/05/22 03:06
今天无意中接触到IntenService。不知其意,于是,百度之。
IntentService 和Service是经常作为比较的对象,不只是是因为有公共的名字“Service”,而且还因为IntentService是继承自Service的。那么,两者究竟有什么样的区别和联系呢。
Service的话,作为android开发者都比较熟悉,它主要用在后台运行。例如:使用UC浏览器上网的时候,天天动听播放着音乐。那么IntentService继承自Service的话,这一作用 也是具备的。
Service 的话在主线程中,所以它不能处理耗时太多的操作,如果需要处理耗时太多的操作的话,那么则需要另外开发线程进行处理;比如说操作数据库、连接网络等。
而IntentService的话,它本身对于数据的处理另外开辟了线程进行处理,所以我的理解是它对Service做了一个很好的封装。它的实现机制是首先,创建一个消息队列,如果有任务需要进行处理的话,那么首先将任务加载到消息队列中,而真正处理消息的则在WrokThread线程中。通过先来先服务的方式对消息进行处理。
以下是两者关系示意图:
两者的实现方式大体差不多,细节上有所不同,先来看看IntentService
我们需要进行耗时操作处理的话。继承IntentService。然后重写onHandleIntent 方法。我们的耗时处理实现写于此方法即可。
public class MyIntentService extends IntentService {public MyIntentService() {super("android");}@Overrideprotected void onHandleIntent(Intent intent) {System.out.println("begin");try {Thread.sleep(20000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("end");}}
接着我们再来看Servie
public class MyService extends Service {public void onCreate() {super.onCreate();System.out.println("create");}public void onStart(Intent intent, int startId) {super.onStart(intent, startId);System.out.println("begin");try {Thread.sleep(20000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("end");}@Overridepublic IBinder onBind(Intent intent) {return null;}}
我们在onStart方法中进行处理。但是我们不能处理耗时比较长的操作。如果需要的话,我们必须另起线程进行处理。
再说一句,上述两者都是通过startService方式启动的。
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startService(new Intent(this, MyService.class));startService(new Intent(this, MyIntentService.class));startService(new Intent(this, MyIntentService.class));}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.// getMenuInflater().inflate(R.menu.main, menu);return true;}}
好了,现在我们就知道了IntentService的作用了,它用于后台处理耗时的操作,诸如联网,操作数据库等。
- 你所不知道的IntentService
- 你所不知道list的妙用
- 你所不知道的西安
- 你所不知道的知识
- 你所不知道的华为(z)
- 你所不知道的const
- 告诉你所不知道的typedef
- 告诉你所不知道的typedef
- 你所不知道的台湾宗教
- 你所不知道的8020法则
- 你所不知道的传输层
- 你所不知道的传输层
- 扑克你所不知道的
- 你所不知道的传输层
- java你所不知道的实用技巧
- java你所不知道的实用技巧
- 你所不知道的马云
- 你所不知道的main函数
- Highcharts和EXT中panel结合
- GCC编译选项和环境变量
- Excel插件开发
- uva 11988
- Hadoop下join操作的几点优化意见
- 你所不知道的IntentService
- 常见笔试面试题2
- Win7X64下驱动的测试环境搭建.
- 场效应管的判别、检测及使用时的注意事项!
- MapFile和BloomMapFile文件
- 分形(factal)的基本概念
- struts2 DMI 不起作用的原因
- 使用FileZilla向linux系统上传文件
- Sencha touch 开发;nestedlist以及getItemTextTpl 自定义显示