IntentService处理异步请求和耗时操作

IntentService是Service的子类,用于处理异步请求和耗时操作,避免主线程ANR异常。它在一个单独的工作线程中运行,每次启动IntentService只会创建一个实例,即使多次启动,也只会在后台顺序执行任务。

基本概念

IntentService继承于Service,方便处理异步请求,在IntentService中有一个工作线程来处理耗时操作

如果我们直接把 耗时操作 放到Service中,虽然可以这样做,但是很容易引起ANR异常(Application Not Responding)

这是因为service是运行在主线程中的,有一定的时间限制,如果在主线程中对一个任务的处理时间超过了限制,进程就会出现“应用不响应”异常,即ANR(Application Not Responding)。为了避免这样情况,都会在service里用新的thread处理一些可能需要更多处理时间的任务。

于是Android设计了一种更方便的service + thread模式,即IntentService,通过它可以很方便地实现在service中使用thread进行耗时任务的处理。

在activity中多次启动IntentService,每次启动,都会新建一个工作线程,但始终只有一个IntentService实例

下面这个例子就把耗时操作放到了Service中,然后报出ANR异常

package com.clc.app4;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }
}

 创建一个简单的IntentService

package com.clc.app4;

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

public class MyIntentService extends IntentService {
    public static final String TAG = "MyIntentService";
	
	//要在 AndroidManifest.xml 里声明 servcie,必须提供一个无参构造函数
    public MyIntentService() {
		//IntentService 的构造函数需要提供一个工作线程的名字
        super("MyIntentService");
    }

	//参数intent即startService(intent)中的intent,用于传递信息
    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null){
			//处理异步请求
            String action = intent.getAction();
            if ("fun1".equals(action)) {
                Log.d(TAG, "onHandleIntent: fun1");
            }else if ("fun2".equals(action)) {
                Log.d(TAG, "onHandleIntent: fun2");
            }else if ("fun3".equals(action)) {
                Log.d(TAG, "onHandleIntent: fun3");
            }
        }

		//加入耗时操作,并没有导致ANR异常
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "onHandleIntent: sleep over");
    }
}

启动 IntentService 

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Log.d(TAG, "onCreate: start one service");


        Intent intent1 = new Intent(this,MyIntentService.class);
        intent1.setAction("fun1");
        Intent intent2 = new Intent(this,MyIntentService.class);
        intent1.setAction("fun2");
        Intent intent3 = new Intent(this,MyIntentService.class);
        intent1.setAction("fun3");

//接着启动多次IntentService,并不会创建多个IntentService实例
//由于IntentService只持有一个工作线程,每次启动,并不会创建新的工作线程,只是把任务加入到任务队列中等待执行,按照one-by-one方式处理多个任务请求
        startService(intent1);
        startService(intent2);
        startService(intent3);

        Log.d(TAG, "onCreate: start over");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值