7. If you want to carry on a long-running task, what do you need to do?

IntentService;Service

Service:执行的操作,依然是在UI线程中执行;如果是耗时的操作,或者是阻塞的操作,那么,会阻塞UI线程,造成ANR现象的出现。

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

IntentService: 会创建一个自己的独立线程,区别于UI线程。这样,任何耗时的操作,都可以通过IntentService来实现。

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

IntentService的源码:
在使用的时候,只需要定义一个构造函数,提供一个Name;然后,重写onHandleIntent(Intent)方法,在该方法中,可以写上耗时操作,会导致阻塞的操作。
然后,就可以了。按照使用Service那样使用。但是,耗时操作时放到onHandleIntent(Intent)中。
因为,该方法是在独立线程中执行的,不会影响到UI线程。
-----从下面IntentService的实现可知。
-----如果,有多个耗时操作的执行请求,发送给该IntentService来执行,那么,如何处理呢?
因为,只是创建了一个IntentService,对应只是创建了一个Thread;每次发出执行请求,
系统都会回调该方法:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
也就是,每个执行请求(Intent),变成了每个Message。

每个Message的实际处理,由派生类中的onHandleIntent方法来执行。
所以,即使有多个耗时操作的执行请求,但是每次该IntentService每次只执行一个耗时操作。

IntentService的源码:

package android.app;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

/**
* An abstract {@link Service} that serializes the handling of the Intents passed upon service
* start and handles them on a handler thread.
*
* <p>To use this class extend it and implement {@link #onHandleIntent}. The {@link Service} will
* automatically be stopped when the last enqueued {@link Intent} is handled.
*/
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;

private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}

@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}

public IntentService(String name) {
super();
mName = name;
}

@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();

mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}

@Override
public void onDestroy() {
mServiceLooper.quit();
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

/**
* Invoked on the Handler thread with the {@link Intent} that is passed to {@link #onStart}.
* Note that this will be invoked from a different thread than the one that handles the
* {@link #onStart} call.
*/
protected abstract void onHandleIntent(Intent intent);
}

IntentServicce;Looper;long-running task的更多相关文章

  1. get running task , process and service

    public class MyActivityManager extends ExpandableListActivity { private static final String NAME = & ...

  2. How to:Aborting a long running task in TPL

    http://social.msdn.microsoft.com/Forums/vstudio/en-US/d0bcb415-fb1e-42e4-90f8-c43a088537fb/aborting- ...

  3. asp.net web api long running task

    http://stackoverflow.com/questions/17577016/long-running-task-in-webapi http://blog.stephencleary.co ...

  4. C#并行编程-Task

    菜鸟学习并行编程,参考<C#并行编程高级教程.PDF>,如有错误,欢迎指正. 目录 C#并行编程-相关概念 C#并行编程-Parallel C#并行编程-Task C#并行编程-并发集合 ...

  5. 【转】【C#】【Thread】【Task】多线程

    多线程 多线程在4.0中被简化了很多,仅仅只需要用到System.Threading.Tasks.::.Task类,下面就来详细介绍下Task类的使用. 一.简单使用 开启一个线程,执行循环方法,返回 ...

  6. TaskTracker任务初始化及启动task源码级分析

    在监听器初始化Job.JobTracker相应TaskTracker心跳.调度器分配task源码级分析中我们分析的Tasktracker发送心跳的机制,这一节我们分析TaskTracker接受JobT ...

  7. 【Hadoop代码笔记】Hadoop作业提交之TaskTracker获取Task

    一.概要描述 在上上一篇博文和上一篇博文中分别描述了jobTracker和其服务(功能)模块初始化完成后,接收JobClient提交的作业,并进行初始化.本文着重描述,JobTracker如何选择作业 ...

  8. Hadoop作业提交之TaskTracker获取Task

    [Hadoop代码笔记]Hadoop作业提交之TaskTracker获取Task 一.概要描述 在上上一篇博文和上一篇博文中分别描述了jobTracker和其服务(功能)模块初始化完成后,接收JobC ...

  9. Task Cancellation: Parallel Programming

    http://beyondrelational.com/modules/2/blogs/79/posts/11524/task-cancellation-parallel-programming-ii ...

随机推荐

  1. 总结python 元组和列表的区别

    python的基本类型中有元组和列表这么俩个,但是这哥俩却比较难于区分,今天就来用简单的实例说明两者的不同. 列表:1.使用中括号([ ])包裹,元素值和个数可变 实例: aaa = ['sitena ...

  2. P4编程环境搭建遇到的问题与解决方法

    在经历了无数的折腾之后,算是折腾,最后采用的是陈翔学长的脚本加上可爱的shell调整装好的. 链接:p4Install 也许是ubuntu18.04的问题,也有可能是我自己把这个系统折腾的有点杂乱的原 ...

  3. OSG学习:多重纹理映射

    #include<osgViewer\Viewer> #include<osg\Node> #include<osg\Geode> #include<osg\ ...

  4. java面试95题

    1.面向对象的特征有哪些方面? 答:面向对象的特征主要有以下几个方面: - 抽象:抽象是将一类对象的共同特征总结出来构造类的过程,包括数据抽象和行为抽象两方面.抽象只关注对象有哪些属性和行为,并不关注 ...

  5. Jrebel 工具学习

    Jrebel 可快速实现热部署,节省了大量重启时间,提高了个人开发效率.网上可搜索到破解版. http://baike.baidu.com/link?url=wuzv7Wa7SMUKltJr-dyta ...

  6. Android 布局方式学习

    一.LinearLayout线性布局: 线性布局是程序中最常见的一种布局方式,线性布局可以分为水平线性布局和垂直线性布局两种, 通过android:orientation属性可以设置线性布局的方向 1 ...

  7. jdbc关闭连接顺序

    jdbc连接数据库时,先获取connection,再通过statement进行操作,将结果集放在resultset中,不过在关闭数据库的时候要小心,要跟前面的操作反着来,不然就会出现异常.如果直接关闭 ...

  8. 向今天要结果; 向明天要动力 eclipse不自动弹出提示(alt+/快捷键失效)

    最近公司电脑上的Eclipse没有了自动提示功能,也不是全部不提示,大多数情况下按下“alt+/”键还会产生提示,但是当我在java项目中邪main方法和syso的时候,“alt+/”则会失效,今天在 ...

  9. 【bzoj4195】[Noi2015]程序自动分析 离散化+并查集

    题目描述 在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足. 考虑一个约束满足问题的简化版本:假设x1,x2,x3,…代表程序中出现的变量,给定n个形如xi=xj或xi≠xj的变量 ...

  10. 【bzoj1704】[Usaco2007 Mar]Face The Right Way 自动转身机 贪心

    题目描述 农夫约翰有N(1≤N≤5000)只牛站成一排,有一些很乖的牛朝前站着.但是有些不乖的牛却朝后站着.农夫约翰需要让所有的牛都朝前站着.幸运的是约翰最近买了一个自动转身机.这个神奇的机器能使K( ...