共计 12529 个字符,预计需要花费 32 分钟才能阅读完成。
IntentService
一、IntentService 概述
上一篇咱们聊到了 HandlerThread,本篇咱们就来看看 HandlerThread 在 IntentService 中的利用,看本篇前倡议先看看上篇的 HandlerThread,有助于咱们更好把握 IntentService。同样地,咱们先来看看 IntentService 的特点:
它实质是一种非凡的 Service, 继承自 Service 并且自身就是一个抽象类
它能够用于在后盾执行耗时的异步工作,当工作实现后会主动进行
它领有较高的优先级,不易被零碎杀死(继承自 Service 的缘故),因而比拟适宜执行一些高优先级的异步工作
它外部通过 HandlerThread 和 Handler 实现异步操作
创立 IntentService 时,只需实现 onHandleIntent 和构造方法,onHandleIntent 为异步办法,能够执行耗时操作
二、IntentService 的惯例应用套路
大略理解了 IntentService 的特点后,咱们就来理解一下它的应用形式,先看个案例:
IntentService 实现类如下:
package com.zejian.handlerlooper;
import android.app.IntentService;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.os.Message;
import com.zejian.handlerlooper.util.LogUtils;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
- Created by zejian
- Time 16/9/3.
- Description:
*/
public class MyIntentService extends IntentService {
public static final String DOWNLOAD_URL="download_url";
public static final String INDEX_FLAG="index_flag";
public static UpdateUI updateUI;
public static void setUpdateUI(UpdateUI updateUIInterface){updateUI=updateUIInterface;}
public MyIntentService(){super("MyIntentService");
}
/**
* 实现异步工作的办法
* @param intent Activity 传递过去的 Intent, 数据封装在 intent 中
*/
@Override
protected void onHandleIntent(Intent intent) {
// 在子线程中进行网络申请
Bitmap bitmap=downloadUrlBitmap(intent.getStringExtra(DOWNLOAD_URL));
Message msg1 = new Message();
msg1.what = intent.getIntExtra(INDEX_FLAG,0);
msg1.obj =bitmap;
// 告诉主线程去更新 UI
if(updateUI!=null){updateUI.updateUI(msg1);
}
//mUIHandler.sendMessageDelayed(msg1,1000);
LogUtils.e("onHandleIntent");
}
//---------------------- 重写一下办法仅为测试 ------------------------------------------
@Override
public void onCreate() {LogUtils.e("onCreate");
super.onCreate();}
@Override
public void onStart(Intent intent, int startId) {super.onStart(intent, startId);
LogUtils.e("onStart");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {LogUtils.e("onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {LogUtils.e("onDestroy");
super.onDestroy();}
@Override
public IBinder onBind(Intent intent) {LogUtils.e("onBind");
return super.onBind(intent);
}
public interface UpdateUI{void updateUI(Message message);
}
private Bitmap downloadUrlBitmap(String urlString) {
HttpURLConnection urlConnection = null;
BufferedInputStream in = null;
Bitmap bitmap=null;
try {final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
bitmap= BitmapFactory.decodeStream(in);
} catch (final IOException e) {e.printStackTrace();
} finally {if (urlConnection != null) {urlConnection.disconnect();
}
try {if (in != null) {in.close();
}
} catch (final IOException e) {e.printStackTrace();
}
}
return bitmap;
}
}
通过代码能够看出,咱们继承了 IntentService,这里有两个办法是必须实现的,一个是构造方法,必须传递一个线程名称的字符串,另外一个就是进行异步解决的办法 onHandleIntent(Intent intent) 办法,其参数 intent 能够附带从 activity 传递过去的数据。这里咱们的案例次要利用 onHandleIntent 实现异步下载图片,而后通过回调监听的办法把下载完的 bitmap 放在 message 中回调给 Activity(当然也能够应用播送实现),最初通过 Handler 去更新 UI。上面再来看看 Acitvity 的代码:
activity_intent_service.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
IntentServiceActivity.java
package com.zejian.handlerlooper.util;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import com.zejian.handlerlooper.MyIntentService;
import com.zejian.handlerlooper.R;
/**
- Created by zejian
- Time 16/9/3.
- Description:
*/
public class IntentServiceActivity extends Activity implements MyIntentService.UpdateUI{
/**
* 图片地址汇合
*/
private String url[] = {
"https://img-blog.csdn.net/20160903083245762",
"https://img-blog.csdn.net/20160903083252184",
"https://img-blog.csdn.net/20160903083257871",
"https://img-blog.csdn.net/20160903083257871",
"https://img-blog.csdn.net/20160903083311972",
"https://img-blog.csdn.net/20160903083319668",
"https://img-blog.csdn.net/20160903083326871"
};
private static ImageView imageView;
private static final Handler mUIHandler = new Handler() {
@Override
public void handleMessage(Message msg) {imageView.setImageBitmap((Bitmap) msg.obj);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_service);
imageView = (ImageView) findViewById(R.id.image);
Intent intent = new Intent(this,MyIntentService.class);
for (int i=0;i<7;i++) {// 循环启动工作
intent.putExtra(MyIntentService.DOWNLOAD_URL,url[i]);
intent.putExtra(MyIntentService.INDEX_FLAG,i);
startService(intent);
}
MyIntentService.setUpdateUI(this);
}
// 必须通过 Handler 去更新,该办法为异步办法,不可更新 UI
@Override
public void updateUI(Message message) {mUIHandler.sendMessageDelayed(message,message.what * 1000);
}
}
代码比较简单,通过 for 循环屡次去启动 IntentService,而后去下载图片,留神即便咱们屡次启动 IntentService,但 IntentService 的实例只有一个,这跟传统的 Service 是一样的,最终 IntentService 会去调用 onHandleIntent 执行异步工作。这里可能咱们还会放心 for 循环去启动工作,而实例又只有一个,那么工作会不会被笼罩掉呢?其实是不会的,因为 IntentService 真正执行异步工作的是 HandlerThread+Handler,每次启动都会把下载图片的工作增加到附丽的音讯队列中,最初由 HandlerThread+Handler 去执行。好~,咱们运行一下代码:
每距离一秒去更新图片,接着咱们看一组 log:
从 Log 能够看出 onCreate 只启动了一次,而 onStartCommand 和 onStart 屡次启动,这就证实了之前所说的,启动屡次,但 IntentService 的实例只有一个,这跟传统的 Service 是一样的,最初工作都执行实现后,IntentService 主动销毁。以上便是 IntentService 德应用形式,怎么样,比较简单吧。接着咱们就来剖析一下 IntentService 的源码,其实也比较简单只有 100 多行代码。
三、IntentService 源码解析
咱们先来看看 IntentService 的 onCreate 办法:
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread(“IntentService[” + mName + “]”);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
当第一启动 IntentService 时,它的 onCreate 办法将会被调用,其外部会去创立一个 HandlerThread 并启动它,接着创立一个 ServiceHandler(继承 Handler),传入 HandlerThread 的 Looper 对象,这样 ServiceHandler 就变成能够解决异步线程的执行类了(因为 Looper 对象与 HandlerThread 绑定,而 HandlerThread 又是一个异步线程,咱们把 HandlerThread 持有的 Looper 对象传递给 Handler 后,ServiceHandler 外部就持有异步线程的 Looper,天然就能够执行异步工作了),那么 IntentService 是怎么启动异步工作的呢?其实 IntentService 启动后还会去调用 onStartCommand 办法,而 onStartCommand 办法又会去调用 onStart 办法,咱们看看它们的源码:
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
- You should not override this method for your IntentService. Instead,
- override {@link #onHandleIntent}, which the system calls when the IntentService
- receives a start request.
- @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
从源码咱们能够看出,在 onStart 办法中,IntentService 通过 mServiceHandler 的 sendMessage 办法发送了一个音讯,这个音讯将会发送到 HandlerThread 中进行解决(因为 HandlerThread 持有 Looper 对象,所以其实是 Looper 从音讯队列中取出音讯进行解决,而后调用 mServiceHandler 的 handleMessage 办法),咱们看看 ServiceHandler 的源码:
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);
}
}
这里其实也阐明 onHandleIntent 的确是一个异步解决办法(ServiceHandler 自身就是一个异步解决的 handler 类),在 onHandleIntent 办法执行完结后,IntentService 会通过 stopSelf(int startId)办法来尝试进行服务。这里采纳 stopSelf(int startId)而不是 stopSelf()来进行服务,是因为 stopSelf()会立刻进行服务,而 stopSelf(int startId)会期待所有音讯都解决完后才终止服务。最初看看 onHandleIntent 办法的申明:
protected abstract void onHandleIntent(Intent intent);
到此咱们就晓得了 IntentService 的 onHandleIntent 办法是一个形象办法,所以咱们在创立 IntentService 时必须实现该办法,通过下面一系列的剖析可知,onHandleIntent 办法也是一个异步办法。这里要留神的是如果后台任务只有一个的话,onHandleIntent 执行完,服务就会销毁,但如果后台任务有多个的话,onHandleIntent 执行完最初一个工作时,服务才销毁。最初咱们要晓得每次执行一个后台任务就必须启动一次 IntentService,而 IntentService 外部则是通过音讯的形式发送给 HandlerThread 的,而后由 Handler 中的 Looper 来解决音讯,而 Looper 是按程序从音讯队列中取工作的,也就是说 IntentService 的后台任务时程序执行的,当有多个后台任务同时存在时,这些后台任务会按内部调用的程序排队执行,咱们后面的应用案例也很好阐明了这点。最初贴一下到 IntentService 的全副源码,大家再次感受一下:
/*
- Copyright (C) 2008 The Android Open Source Project
* - Licensed under the Apache License, Version 2.0 (the “License”);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
* - http://www.apache.org/license…
* - Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an “AS IS” BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
*/
package android.app;
import android.annotation.WorkerThread;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
/**
- IntentService is a base class for {@link Service}s that handle asynchronous
- requests (expressed as {@link Intent}s) on demand. Clients send requests
- through {@link android.content.Context#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.
* - <p>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 {@link #onHandleIntent(Intent)}. IntentService
- will receive the Intents, launch a worker thread, and stop the service as
- appropriate.
* - <p>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.
* - <div class=”special reference”>
- <h3>Developer Guides</h3>
- <p>For a detailed discussion about how to create services, read the
- Services developer guide.</p>
- </div>
* - @see android.os.AsyncTask
*/
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
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);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
* <p>If enabled is true,
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_REDELIVER_INTENT}, so if this process dies before
* {@link #onHandleIntent(Intent)} returns, the process will be restarted
* and the intent redelivered. If multiple Intents have been sent, only
* the most recent one is guaranteed to be redelivered.
*
* <p>If enabled is false (the default),
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
* dies along with it.
*/
public void setIntentRedelivery(boolean enabled) {mRedelivery = enabled;}
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
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) {Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
public IBinder onBind(Intent intent) {return null;}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
*/
@WorkerThread
protected abstract void onHandleIntent(Intent intent);
}
此 IntentService 的源码就剖析完了,嗯,本篇完结。
本文转自 https://blog.csdn.net/javazej…,如有侵权,请分割删除。