Android开发经验谈Android开发

017 Android多线程-IntentService-使用

2021-01-10  本文已影响0人  凤邪摩羯

前言

IntentServcie作为Service的一个子类,可以看做是Service和HandlerThread的结合体,在完成了使命之后会自动停止,适合需要在工作线程处理UI无关任务的场景。那么今天就来讲讲IntentServcie的相关知识吧。

今天涉及的知识点:

  1. IntentService特点
  2. IntentService工作流程
  3. IntentService使用步骤
  4. IntentService的使用
  5. IntentService注意项
  6. WorkService后台处理效果图和项目结构图
  7. WorkService 和 MainActivity中使用源码

先来波运行效果图

image

一.IntentService特点

二.IntentService工作流程

IntentService工作流程流程如下:

image

三. IntentService使用步骤

IntentService使用步骤如下:

  1. 新建service类并继承自IntentService
  2. 实现service的构造方法
  3. 在manifast.xml中注册服务
  4. 在服务的onHandleIntent方法中实现业务逻辑

四.IntentService的使用

下面以一个例子讲解IntentService的使用。

4.1 新建WorkService继承自IntentService

代码如下:

public class WorkService extends IntentService {

    public WorkService() {
        //必须实现父类的构造方法
        super("WorkService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

    }

}

这里需要注意的是,必须实现WorkService的构造方法,然后一般在 super方法中写入但当前servcie的类名,以作标志。

4.2 manifast.xml中注册WorkService

IntentService作为Service的子类,但仍然是一个Service,所以我们需要在manifast.xml中注册服务:

    </application
       //其他代码省略
       //......   
    >
        <service android:name="com.example.function.WorkService">
            <intent-filter>
                <action android:name="com.example.function.WorkService"/>
            </intent-filter>
        </service>

       //其他代码省略
       //......
    </application>

这里需要注意的是 service标签中和action标签中的name属性要保持唯一性,我一般用当前service类的全路径表示。

4.3 在MainActivity中启动WorkService

一切弄好后,就开始在MainActivity中启动WorkService了,在MainActivity中启动主要代码如下:

        //所有的耗时任务都将在onHandleIntent中处理
        Intent intent=new Intent(MainActivity.this, WorkService.class);
        intent.putExtra("taskId",1);
        startService(intent);

五 IntentService注意项

IntentService使用时需要注意的是:

  1. 如果IntentService启动多次,每个耗时操作会以队列形式在IntentService 的 onHandleIntent方法中依次执行,串行执行方式结束后,IntentService自动销毁。
  2. IntentService的启动要使用"非绑定模式",若以“绑定”模式启动,将不会走IntentService的onHandleIntent方法,所以要以"非绑定模式"启动

六 WorkService后台处理效果图和项目结构图

效果图

image

项目结构图

image
上一篇下一篇

猜你喜欢

热点阅读