四大组件之特殊Service(IntentService)的使用

来源:互联网 发布:子弹图纸尺寸图片编程 编辑:程序博客网 时间:2024/04/30 09:24

在Service中,通常是不需要同时处理多个请求的,在这种情况下,使用IntentService或许是最好的选择。为什么呢?下面的这个问题给出了答案。

IntentService如何使用?和Service有什么区别?
IntentService里面是默认自带一条线程的,无需自己去new子线程,而且是和主线程分离的,使用的时候只需要处理onHandleIntent()这个方法即可。不需要去写onCreate(),也不需要去写onStartCommand(),而且在任务执行结束后,会自行调用stopSelf()方法来关闭Service。IntentService适用于单线程去完成任务,而且不会阻塞主线程。

MainActivity代码,很简单,启动Service:

package com.example.lenovo.demo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    /**     * 开启服务,进行下载     */    public void downLoad(View view){        startService(new Intent(this,MyService.class));    }}

MyService代码:

package com.example.lenovo.demo;import android.app.IntentService;import android.content.Intent;/** * Created by shan on 2016/7/23. * */public class MyService extends IntentService {    /**     * Creates an IntentService.  Invoked by your subclass's constructor.     * 这里需要一个空的构造方法     */    public MyService() {        super("");    }    @Override    protected void onHandleIntent(Intent intent) {        //无需new子线程,直接进行耗时操作:do something        //任务完成后也无需关闭Service,源码内部已经实现stopSelf()    }}

最后,配置清单文件,静态注册Service,添加所需的权限即可。具体的耗时代码就不写了~~

0 0