Android IntentService全然解析 当Service遇到Handler
转载请标明出处:
http://blog.csdn.net/lmj623565791/article/details/47143563;
本文出自:【张鸿洋的博客】
一 概述
大家都清楚。在Android的开发中。凡是遇到耗时的操作尽可能的会交给Service去做,比方我们上传多张图,上传的过程用户可能将应用置于后台。然后干别的去了,我们的Activity就非常可能会被杀死,所以能够考虑将上传操作交给Service去做,假设操心Service被杀,还能通过设置startForeground(int, Notification)方法提升其优先级。
那么。在Service里面我们肯定不能直接进行耗时操作。一般都须要去开启子线程去做一些事情。自己去管理Service的生命周期以及子线程并不是是个优雅的做法;好在Android给我们提供了一个类,叫做IntentService,我们看下凝视。
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.
意思说IntentService是一个基于Service的一个类。用来处理异步的请求。你能够通过startService(Intent)来提交请求。该Service会在须要的时候创建,当完毕全部的任务以后自己关闭,且请求是在工作线程处理的。
这么说,我们使用了IntentService最起码有两个优点。一方面不须要自己去new Thread了;还有一方面不须要考虑在什么时候关闭该Service了。
好了,那么接下来我们就来看一个完整的样例。
二 IntentService的使用
我们就来演示一个多个图片上传的案例,当然我们会模拟上传的耗时。毕竟我们的重心在IntentService的使用和源代码解析上。
首先看下效果图
效果图
每当我们点击一次button。会将一个任务交给后台的Service去处理,后台的Service每处理完毕一个请求就会反馈给Activity,然后Activity去更新UI。当全部的任务完毕的时候,后台的Service会退出,不会占领不论什么内存。
Service
package com.zhy.blogcodes.intentservice;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class UploadImgService extends IntentService
{
private static final String ACTION_UPLOAD_IMG = "com.zhy.blogcodes.intentservice.action.UPLOAD_IMAGE";
public static final String EXTRA_IMG_PATH = "com.zhy.blogcodes.intentservice.extra.IMG_PATH";
public static void startUploadImg(Context context, String path)
{
Intent intent = new Intent(context, UploadImgService.class);
intent.setAction(ACTION_UPLOAD_IMG);
intent.putExtra(EXTRA_IMG_PATH, path);
context.startService(intent);
}
public UploadImgService()
{
super("UploadImgService");
}
@Override
protected void onHandleIntent(Intent intent)
{
if (intent != null)
{
final String action = intent.getAction();
if (ACTION_UPLOAD_IMG.equals(action))
{
final String path = intent.getStringExtra(EXTRA_IMG_PATH);
handleUploadImg(path);
}
}
}
private void handleUploadImg(String path)
{
try
{
//模拟上传耗时
Thread.sleep(3000);
Intent intent = new Intent(IntentServiceActivity.UPLOAD_RESULT);
intent.putExtra(EXTRA_IMG_PATH, path);
sendBroadcast(intent);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
@Override
public void onCreate()
{
super.onCreate();
Log.e("TAG","onCreate");
}
@Override
public void onDestroy()
{
super.onDestroy();
Log.e("TAG","onDestroy");
}
}
代码非常短。主要就是继承IntentService。然后复写onHandleIntent方法,依据传入的intent来选择详细的操作。
startUploadImg是我写的一个辅助方法,省的每次都去构建Intent,startService了。
Activity
package com.zhy.blogcodes.intentservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zhy.blogcodes.R;
public class IntentServiceActivity extends AppCompatActivity
{
public static final String UPLOAD_RESULT = "com.zhy.blogcodes.intentservice.UPLOAD_RESULT";
private LinearLayout mLyTaskContainer;
private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction() == UPLOAD_RESULT)
{
String path = intent.getStringExtra(UploadImgService.EXTRA_IMG_PATH);
handleResult(path);
}
}
};
private void handleResult(String path)
{
TextView tv = (TextView) mLyTaskContainer.findViewWithTag(path);
tv.setText(path + " upload success ~~~ ");
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_service);
mLyTaskContainer = (LinearLayout) findViewById(R.id.id_ll_taskcontainer);
registerReceiver();
}
private void registerReceiver()
{
IntentFilter filter = new IntentFilter();
filter.addAction(UPLOAD_RESULT);
registerReceiver(uploadImgReceiver, filter);
}
int i = 0;
public void addTask(View view)
{
//模拟路径
String path = "/sdcard/imgs/" + (++i) + ".png";
UploadImgService.startUploadImg(this, path);
TextView tv = new TextView(this);
mLyTaskContainer.addView(tv);
tv.setText(path + " is uploading ...");
tv.setTag(path);
}
@Override
protected void onDestroy()
{
super.onDestroy();
unregisterReceiver(uploadImgReceiver);
}
}
Activity中,每当我点击一次button调用addTask,就回模拟创建一个任务。然后交给IntentService去处理。
注意。当Service的每一个任务完毕的时候。会发送一个广播。我们在Activity的onCreate和onDestroy里面分别注冊和解注冊了广播;当收到广播则更新指定的UI。
布局文件
<LinearLayout android:id="@+id/id_ll_taskcontainer"
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"
android:orientation="vertical"
>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="addTask" android:text="add Task"/>
</LinearLayout>
ok,这样我们就完毕了我们的效果图的需求。通过上例。大家能够看到我们能够使用IntentService非常方便的处理后台任务,屏蔽了诸多细节;而Service与Activity通信呢,我们选择了广播的方式(当然这里也能够使用LocalBroadcastManager)。
学会了使用之后。我们再一鼓作气的看看其内部的实现。
三 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/licenses/LICENSE-2.0
*
* 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.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
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);
}
}
public IntentService(String name) {
super();
mName = name;
}
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@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) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@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();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
protected abstract void onHandleIntent(Intent intent);
}
能够看到它在onCreate里面初始化了一个HandlerThread,关于HandlerThread的使用和源代码
分析參考:Android HandlerThread 全然解析,看到这预计已经能猜到它的逻辑了:
就是每次调用onStartCommand的时候,通过mServiceHandler发送一个消息。消息中包括我们的intent。然后在该mServiceHandler的handleMessage中去回调onHandleIntent(intent);就能够了。
那么我们详细看一下源代码,果然是这样,onStartCommand中回调了onStart,onStart中通过mServiceHandler发送消息到该handler的handleMessage中去。最后handleMessage中回调onHandleIntent(intent)。
注意下:回调完毕后回调用 stopSelf(msg.arg1),注意这个msg.arg1是个int值。相当于一个请求的唯一标识。
每发送一个请求,会生成一个唯一的标识。然后将请求放入队列。当全部运行完毕(最后一个请求也就相当于getLastStartId == startId),或者当前发送的标识是近期发出的那一个(getLastStartId == startId)。则会销毁我们的Service.
假设传入的是-1则直接销毁。
那么。当任务完毕销毁Service回调onDestory。能够看到在onDestroy中释放了我们的Looper:mServiceLooper.quit()。
ok~ 假设你的需求能够使用IntentService来做,能够尽可能的使用,设计的还是相当赞的。当然了,假设你须要考虑并发等等需求。那么可能须要自己去扩展创建线程池等。
ok~~
欢迎关注我的微博http://weibo.com/u/3165018720
群号:463081660,欢迎入群
微信公众号:hongyangAndroid
(欢迎关注,第一时间推送博文信息)
Android IntentService全然解析 当Service遇到Handler的更多相关文章
- Android IntentService完全解析 当Service遇到Handler
一 概述 大家都清楚,在Android的开发中,凡是遇到耗时的操作尽可能的会交给Service去做,比如我们上传多张图,上传的过程用户可能将应用置于后台,然后干别的去了,我们的Activity就很可能 ...
- Android ActionBar全然解析,使用官方推荐的最佳导航栏(上)
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/18234477 本篇文章主要内容来自于Android Doc.我翻译之后又做了些加工 ...
- Android Volley全然解析(四),带你从源代码的角度理解Volley
版权声明:本文出自郭霖的博客,转载必须注明出处. https://blog.csdn.net/sinyu890807/article/details/17656437 转载请注明出处:http://b ...
- Android DiskLruCache全然解析,硬盘缓存的最佳方案
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/28863651 概述 记得在非常早之前.我有写过一篇文章Android高效载入大图. ...
- Android ViewDragHelper全然解析 自己定义ViewGroup神器
转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/46858663. 本文出自:[张鸿洋的博客] 一.概述 在自己定义ViewGro ...
- Android DiskLruCache 源代码解析 硬盘缓存的绝佳方案
转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/47251585: 本文出自:[张鸿洋的博客] 一.概述 依然是整理东西.所以最近 ...
- 【转载】Android IntentService使用全面介绍及源码解析
一 IntentService介绍 IntentService定义的三个基本点:是什么?怎么用?如何work? 官方解释如下: //IntentService定义的三个基本点:是什么?怎么用?如何wo ...
- Android ListView工作原理全然解析,带你从源代码的角度彻底理解
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/44996879 在Android全部经常使用的原生控件其中.使用方法最复杂的应该就是 ...
- Android安全攻防战,反编译与混淆技术全然解析(下)
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/50451259 在上一篇文章其中,我们学习了Android程序反编译方面的知识,包括 ...
随机推荐
- Python_Tips[6] -> is 和 == 的区别
is和==的区别 / Difference between is and == 对于Python的对象来说,具有id/type/value三种特性,而在判断两个相等的is和==中,分别是对对象的id和 ...
- 「kuangbin带你飞」专题十五 数位DP
传送门 A.CodeForces - 55D Beautiful numbers 题意 一个正整数是 漂亮数 ,当且仅当它能够被自身的各非零数字整除.我们不必与之争辩,只需计算给定范围中有多少个漂亮数 ...
- hdu6035(树形DP)
hdu6035 题意 给出一棵树,现在定义两点之间距离为两点间最短路径上颜色集合的大小.问任意两点间距离之和. 分析 换个方向,题目其实等价于求每种颜色在多少条路径上出现过(每种颜色对于答案的贡献), ...
- 洛谷——P1143 进制转换
P1143 进制转换 题目描述 请你编一程序实现两种不同进制之间的数据转换. 输入输出格式 输入格式: 输入数据共有三行,第一行是一个正整数,表示需要转换的数的进制n(2≤n≤16),第二行是一个n进 ...
- 利用MAP动态创建C++类对象
MFC的CRuntimeClass利用链表实现了C++类的动态创建.但是如果项目中对动态创建的要求比较低,我们完全可以利用map实现简单的动态创建. http://blog.csdn.net/yeji ...
- 警告Conversion specifies type'int' but the argument has type'size_t'
代码: #import<Foundation/Foundation.h> int main(int argc,const char * argv[]){ const char *words ...
- 5.Android之NFC介绍
NFC简介: Near Field Communication 近场通信,是一种数据传输技术. 与wifi.蓝牙.红外线等数据传输技术的一个主要差异就是有效距离一般不能超过4cm. NFC支持3种工作 ...
- python 时间 相关
http://www.jb51.net/article/47957.htm 不管何时何地,只要我们编程时遇到了跟时间有关的问题,都要想到 datetime 和 time 标准库模块,今天我们就用它内部 ...
- 6、Python模块
最常用的两个模块: os #可以允许python调用执行系统命令,如shell sys #处理与python程序本身的事情 Python自带200多个常用模块 Python官网收集了2 ...
- setInterval/setTimeout传参方法
网上文章说有3种方法,对于我来说一种方法就够了: <script> var user_name='离间计' //定时器 异步运行 function hello(name){ alert(n ...
