安卓中实现异步任务(5)——使用IntentService实现

问题背景

上篇文章大致介绍了几种安卓汇总实现异步任务的方法,讲得比较简要,有朋友问到具体的实现方式,现在开始分列几篇文章详细介绍这几种异步的具体实现。这篇讲得是基于IntentService实现,持续更新。

问题分析

在日常安卓开发汇总,我们在使用 Service 时如果要执行耗时任务,总会创建一个子线程来执行,而不是直接在 Service中执行。这是因为 Service 中的程序仍然运行于主线程中,当执行一项耗时操作时,很容易导致ANR错误。当需要与 UI线程进行交互时,使用 Handler 机制来进行处理。 为了简化操作,Android提供了IntentService类。IntentService是 Android中提供的后台服务类,是Service 自动实现多线程的子类。首先,我们一起来看看具体怎么使用。

实现demo

(1)新建我们的IntentService子类,在onHandleIntent中执行耗时任务,代码如下:

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyIntentService extends IntentService {
    private static final String TAG = "MyIntentService";
    int i = 3;
    //构造方法
    public MyIntentService() {
        super("");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        while (i > 0) {
            Log.d(TAG, "onHandleIntent i : " + i);
            i--;
            try {
                // 模拟耗时任务
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
    }
}

注意:IntentService是service的子类,定义后要记得在manifest配置文件中进行注册: <service android:name=".thread.MyIntentService"/> (2)新建activity,对应layout布局文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".thread.IntentServiceActivity">
    <Button
        android:id="@+id/startIntentService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="启动IntentService"
        android:onClick="startIntentService"
        android:gravity="center_horizontal"/>


</LinearLayout>

布局比较简单,就是一个button用来启动我们的intentservice。 (3)对应activity代码如下:

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class IntentServiceActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_service);
    }

    public void startIntentService(View view) {
        //启动service
        Intent intent = new Intent(IntentServiceActivity.this, MyIntentService.class);
        startService(intent);
    }
}

(4)执行APP log如下: image.png

关键代码分析

持续更新。。。