[Android Pro] Android异步任务处理之AsyncTaskLoader的使用
reference to : http://blog.csdn.net/happy_horse/article/details/51518280
最近项目中涉及到加载本地的地名.db文件,数据量大,自然不能直接放在UI线程中操作,好在Google在Android3.0以后,提供了AsyncTaskLoader来做一些耗时的异步任务。
一 官方对AsyncTaskLoader的定义及特点介绍如下:
Abstract Loader that provides an AsyncTask to do the work
Introduced in Android 3.0, loaders make it easy to asynchronously load data in an activity or fragment. Loaders have these characteristics:
1、They are available to every Activity and Fragment.
//支持Activity和Fragment
2、They provide asynchronous loading of data.
//异步下载 (就是不影响UI线程)
3、They monitor the source of their data and deliver new results when the content changes.
//当数据源改变时能及时通知客户端
4、They automatically reconnect to the last loader’s cursor when being
recreated after a configuration change. Thus, they don’t need to
re-query their data.
//发生configuration change时自动重连接
二 实际项目介绍
下面引用官方的一个展示当前设备所有已安装应用程序的DEMO,来对AsyncTaskLoader的用法做一个详细的介绍:
项目结构如图:
第一步:我们需要写一个对应于每一个应用程序的实体类,该实体类包含应用程序图标和标签两个属性。
AppEntry.java:
/**
* Created by Administrator on 2016/5/25.
*/
public class AppEntry {
private String mLabel;//应用文字标签
private Drawable mIcon;//应用图标 private final AppListLoader mLoader;
private final ApplicationInfo mInfo;//<application>节点信息,只有一个
//PackageInfo、ApplicationInfo、ActivityInfo、ResolveInfo四种信息类的一种
private final File mApkFile; private boolean mMounted; public AppEntry(AppListLoader mLoader,ApplicationInfo mInfo ) {
this.mInfo = mInfo;
this.mLoader = mLoader;
mApkFile=new File(mInfo.sourceDir);//sourceDir=Full path to the location of this package
} public ApplicationInfo getApplicationInfo() {
return mInfo;
} public String getLabel() {
return mLabel;
} public Drawable getIcon() {
if (mIcon == null) {
if (mApkFile.exists()) {
mIcon = mInfo.loadIcon(mLoader.mPm);
//public Drawable loadIcon (PackageManager pm){}获取应用图标
return mIcon;
} else {
mMounted = false;
}
} else if (!mMounted) {
// If the app wasn't mounted but is now mounted, reload its icon.
if (mApkFile.exists()) {
mMounted = true;
mIcon = mInfo.loadIcon(mLoader.mPm);
return mIcon;
}
} else {
return mIcon;
} return mLoader.getContext().getResources()
.getDrawable(android.R.drawable.sym_def_app_icon);//否则返回默认的小机器人
} @Override
public String toString() {
return mLabel;
} void loadLabel(Context context) {
if (mLabel == null || !mMounted) {
if (!mApkFile.exists()) {
mMounted = false;
mLabel = mInfo.packageName;//获取程序名称
} else {
mMounted = true;
CharSequence label = mInfo.loadLabel(context.getPackageManager());
mLabel = label != null ? label.toString() : mInfo.packageName;
}
}
}
}
第二步:需要写一个自己的AppListLoader ,继承自AsyncTaskLoader,并实现其相关抽象方法。
(1)onStartLoading:注册一些监听器到loader上,并且执行一次forceLoad(); 否则loader不会开始工作
(2)loadInBackground:不用说,在这里就是加载数据并且返回,其实这个数据就返回到了LoaderManager的onLoadFinished方法第二个参数
(3)onStopLoading:停止加载数据,但不要停止监听也不要释放数据,就可以随时重启loader
(4)onReset:先确保已经停止加载数据了,然后释放掉监听器并设为null
(5)onCanceled: 在这里可以释放资源,如果是list就不需要做什么了,但是象cursor或者打开了什么文件就应该关闭一下;
AppListLoader .java:
public class AppListLoader extends AsyncTaskLoader<List<AppEntry>> {
private static final String TAG = "ADP_AppListLoader";
private static final boolean DEBUG = true;
final PackageManager mPm;//包管理器
private List<AppEntry> mApps;//装在应用程序实体的容器
// An observer to notify the Loader when new apps are installed/updated.
private InstalledAppsObserver mAppsObserver;//非系统应用程序安装或者卸载的广播接收器
// The observer to notify the Loader when the system Locale has been changed.
private SystemLocaleObserver mLocaleObserver;//系统应用程序安装或者卸载的广播接收器
public AppListLoader(Context context) {
super(context);
mPm = getContext().getPackageManager();
Log.i("TAG","AppListLoader(Context)");
}
@Override
protected void onStartLoading() {
Log.i("TAG","onStartLoading()");
if(mApps!=null){
deliverResult(mApps);
}
// Register the observers that will notify the Loader when changes are made.
if (mAppsObserver == null) {
mAppsObserver = new InstalledAppsObserver(this);//注册一个非系统应用程序的接收器
}
if (mLocaleObserver == null) {
mLocaleObserver = new SystemLocaleObserver(this);//注册一个系统应用程序的接收器
}
if (takeContentChanged()) {
forceLoad();
} else if (mApps == null) {
forceLoad();//强制加载数据
}
}
@Override
public void forceLoad() {
Log.i("TAG","forceLoad()");
super.forceLoad();
}
@Override
public List<AppEntry> loadInBackground() {
Log.i("TAG","loadInBackground()");
List<ApplicationInfo> apps=mPm.getInstalledApplications(0);
// public static final int FILTER_ALL_APP = 0; // 所有应用程序
// public static final int FILTER_SYSTEM_APP = 1; // 系统程序
// public static final int FILTER_THIRD_APP = 2; // 第三方应用程序
// public static final int FILTER_SDCARD_APP = 3; // 安装在SDCard的应用程序
if(apps==null){
apps=new ArrayList<>();
}
List<AppEntry> entries=new ArrayList<>(apps.size());
//开始加载数据
for(int i=0;i<apps.size();i++){
AppEntry appEntry=new AppEntry(this,apps.get(i));
appEntry.loadLabel(getContext());
entries.add(appEntry);
}
//Sort the list
Collections.sort(entries,ALPHA_COMPARATOR);//对应用程序进行排序
return entries;
}
@Override
public void deliverResult(List<AppEntry> datas) {//分发loadInBackground()方法返回的结果
Log.i("TAG","deliverResult()");
if(isReset()){
if(datas!=null){
releaseResources(datas);//可以释放相关资源
return;
}
}
List<AppEntry> oldApps=mApps;
mApps=datas;
if(isStarted()){
super.deliverResult(datas);
}
if(oldApps!=null&&oldApps!=datas){
releaseResources(oldApps);
}
}
@Override
protected void onStopLoading() {//停止加载数据
Log.i("TAG","onStopLoading()");
cancelLoad();
}
@Override
protected void onReset() {
Log.i("TAG","onReset()");
onStopLoading();
// At this point we can release the resources associated with 'apps'.
if (mApps != null) {
releaseResources(mApps);
mApps = null;
}
// The Loader is being reset, so we should stop monitoring for changes.
if (mAppsObserver != null) {
getContext().unregisterReceiver(mAppsObserver);//注销广播接收器
mAppsObserver = null;
}
if (mLocaleObserver != null) {
getContext().unregisterReceiver(mLocaleObserver);//注销广播接收器
mLocaleObserver = null;
}
}
@Override
public void onCanceled(List<AppEntry> apps) { // Attempt to cancel the current asynchronous load.
super.onCanceled(apps);
Log.i("TAG","onCanceled()");
releaseResources(apps);
}
/**
* Helper method to take care of releasing resources associated with an
* actively loaded data set.
*/
private void releaseResources(List<AppEntry> apps) {
// For a simple List, there is nothing to do. For something like a Cursor,
// we would close it in this method. All resources associated with the
// Loader should be released here.
}
/**
* Performs alphabetical comparison of {@link AppEntry} objects. This is
* used to sort queried data in {@link }.
*/
private static final Comparator<AppEntry> ALPHA_COMPARATOR = new Comparator<AppEntry>() {
Collator sCollator = Collator.getInstance();
@Override
public int compare(AppEntry object1, AppEntry object2) {
return sCollator.compare(object1.getLabel(), object2.getLabel());
}
};
}
第三步:在MainActivity中调用AsyncTaskLoader,并继承LoaderManager.LoaderCallbacks的接口,重写接口方法:
(1)onCreateLoader: 这个是创建一个AsyncTaskLoader并返回,我们在里面new一个自己写的AppListLoader并返回就OK了;
(2)onLoadFinished: 这个是加载完成后可以更新UI,在这里就是setAdapter了 而这个加载过程其实就是在CursorLoader里面完成的,
只不过系统帮我们完成了,而如果自定义loader的话就要自己完成,这就是区别;
(3)onLoaderReset: loader的重置,在这里一般让UI不显示数据就行;
MainActivity .java:
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//将AppListFragment添加到当前的activity里
FragmentManager fm=getSupportFragmentManager();
if(fm.findFragmentById(android.R.id.content)==null){
AppListFragment list=new AppListFragment();
fm.beginTransaction().add(android.R.id.content,list).commit();
}
}
//实现LoaderManager.LoaderCallbacks的接口
public static class AppListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<AppEntry>>{
private static final String TAG = "ADP_AppListFragment";
private static final boolean DEBUG = true;
private AppListAdapter mAdapter;
private static final int LOADER_ID = 1;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mAdapter=new AppListAdapter(getActivity());
setEmptyText("No Applications");
setListAdapter(mAdapter);
setListShown(false);
if (getLoaderManager().getLoader(LOADER_ID) == null) {
Log.i("TAG", "Initializing the new Loader...");
} else {
Log.i("TAG", "Reconnecting with existing Loader (id '1')...");
}
getLoaderManager().initLoader(LOADER_ID, null, this);
}
@Override
public Loader<List<AppEntry>> onCreateLoader(int id, Bundle args) {
Log.i("TAG", "onCreateLoader()");
return new AppListLoader(getActivity());
}
@Override
public void onLoadFinished(Loader<List<AppEntry>> loader, List<AppEntry> data) {
Log.i("TAG", "onLoadFinished()");
mAdapter.setData(data);
if(isResumed()){
setListShown(true);
}else {
setListShownNoAnimation(true);
}
}
@Override
public void onLoaderReset(Loader<List<AppEntry>> loader) {
Log.i("TAG", "onLoaderReset()");
mAdapter.setData(null);
}
}
然后运行程序如下:
打开应用,AppListLoader中核心方法执行的先后顺序:
05-25 12:57:46.050 11184-11184/com.troy.applistloader I/TAG: +++ Calling initLoader()! +++
05-25 12:57:46.050 11184-11184/com.troy.applistloader I/TAG: +++ Initializing the new Loader... +++
05-25 12:57:46.050 11184-11184/com.troy.applistloader I/TAG: onCreateLoader()
05-25 12:57:46.050 11184-11184/com.troy.applistloader I/TAG: onStartLoading()
05-25 12:57:46.060 11184-11184/com.troy.applistloader I/TAG: forceLoad()
05-25 12:57:46.060 11184-13196/com.troy.applistloader I/TAG: loadInBackground()
05-25 12:57:47.530 11184-11184/com.troy.applistloader I/TAG: deliverResult()
05-25 12:57:47.530 11184-11184/com.troy.applistloader I/TAG: onLoadFinished()
返回键,会执行的方法及执行顺序:
05-25 13:00:08.790 11184-11184/com.troy.applistloader I/TAG: onStopLoading()
05-25 13:00:08.790 11184-11184/com.troy.applistloader I/TAG: onLoaderReset()
05-25 13:00:08.790 11184-11184/com.troy.applistloader I/TAG: onReset()
05-25 13:00:08.790 11184-11184/com.troy.applistloader I/TAG: onStopLoading()
三 总结
本项目的学习之后,我们应该掌握以下几点:
(1)理解AsyncTaskLoader的每一个核心方法的作用及调用时机,以及如何自定义一个AsyncTaskLoader。
(2)如何在Fragement中启动AsyncTaskLoader,继承LoaderManager.LoaderCallbacks,实现接口的三个方法。
(3)应该了解AsyncTaskLoader的底层实际上是执行的AsyncTask,这个可以看看源码。
(4)如何应用ApplicationInfo,获取相关的程序信息。
[Android Pro] Android异步任务处理之AsyncTaskLoader的使用的更多相关文章
- [Android Pro] Android开发实践:自定义ViewGroup的onLayout()分析
reference to : http://www.linuxidc.com/Linux/2014-12/110165.htm 前一篇文章主要讲了自定义View为什么要重载onMeasure()方法( ...
- [Android Pro] Android开发实践:为什么要继承onMeasure()
reference to : http://www.linuxidc.com/Linux/2014-12/110164.htm Android开 发中偶尔会用到自定义View,一般情况下,自定义Vie ...
- [Android Pro] android 4.4 Android原生权限管理:AppOps
reference : http://m.blog.csdn.net/blog/langzxz/45308199 reference : http://blog.csdn.net/hyhyl1990/ ...
- [Android Pro] Android 4.1 使用 Accessibility实现免Root自动批量安装功能
reference to : http://www.infoq.com/cn/articles/android-accessibility-installing?utm_campaign=info ...
- [Android Pro] Android 4.3 NotificationListenerService使用详解
reference to : http://blog.csdn.net/yihongyuelan/article/details/40977323 概况 Android在4.3的版本中(即API 18 ...
- [Android Pro] Android签名与认证详细分析之二(CERT.RSA剖析)
转载自: http://www.thinksaas.cn/group/topic/335449/ http://blog.csdn.net/u010571535/article/details/899 ...
- [Android Pro] android 杀死进程的方法
1: 杀死自己进程的方法 android.os.Process.killProcess(Process.myPid()); 2:杀死别人进程的方法(不能杀死自己) -------a: activity ...
- [Android Pro] Android权限设置android.permission完整列表
android.permission.ACCESS_CHECKIN_PROPERTIES允许读写访问"properties”表在checkin数据库中,改值可以修改上传( Allows re ...
- [Android Pro] Android的Animation之LayoutAnimation使用方法
用于为一个里面的控件,或者是一个里面的控件设置动画效果,可以在文件中设置,亦可以在代码中设置. 一种直接在XML文件中设置 1. 在res/anim文件夹下新建一个XML文件,名为list_anim ...
- [Android Pro] android中permission_group与permisson区别、作用
转载:http://blog.csdn.net/feng88724/article/details/6409313 其实Android在定义 permission 时, 为每个Permission都进 ...
随机推荐
- Bzoj3894 文理分科
Time Limit: 10 Sec Memory Limit: 512 MBSubmit: 667 Solved: 389 Description 文理分科是一件很纠结的事情!(虽然看到这个题 ...
- CSS中清除浮动的两种方式
在CSS中,父元素中的子元素如果使用了float,会导致父元素塌陷,高度为0. 对于这种情况,常见的解决方式有两种. 一.增加新的div,应用clear:both属性 html: <div cl ...
- 数据结构作业——expectation(树形dp+dfs)
expectation Description 给出一棵带权值的树,我们假设从某个节点出发,到目标节点的时间为两个节点之间的最短路.由于出发节点不好选取,所以选在每个节点都有一定的概率,现在我们要求从 ...
- UP Board 妄图启动ubilinux失败
前言 原创文章,转载引用务必注明链接. 经历了上次的上电开机失败,我们终于发现需要手动为UP板安装系统,因为没有显示器的Headless模式时,使用Linux比较方便,另外熟悉Debian系的,所以选 ...
- 机器学习——利用K-均值聚类算法对未标注数据分组
聚类是一种无监督的学习,它将相似的对象归到同一簇中.它有点像全自动分类.聚类方法几乎可以应用到所有对象,簇内的对象越相似,聚类的效果越好. K-均值(K-means)聚类算法,之所以称之为K-均值是因 ...
- 【ASP.NET程序员福利】打造一款人见人爱的ORM(二)
上一篇我已经给大家介绍AntORM的框架[ASP.NET程序员福利]打造一款人见人爱的ORM(一),今天就来着重介绍一下如何使用这套框架 1>AntORM 所有成员 如果你只想操作一种数据库,可 ...
- 基于MQTT协议进行应用开发
官方协议有句如下的话来形容MQTT的设计思想: "It is designed for connections with remote locations where a "sma ...
- SQL 删除索引错误
SQL Server 数据库执行 ”DROP INDEX 索引名 ON 表名“ 时出现“不允许对索引 '索引名' 显式地使用 DROP INDEX.该索引正用于 PRIMARY KEY 约束的强制执行 ...
- 我们是怎么管理QQ群的
文章背景:腾讯平台上的qq群数以千万百万计,但99%的在吹水扯蛋,从早上的问好开始,到晚上的晚安,无一不浪费青春之时间,看之痛心,无力改变,只好自己建了一个,希望能以此来改变群内交流的氛围或环境. 以 ...
- 关于MapReduce中自定义分组类(三)
Job类 /** * Define the comparator that controls which keys are grouped together * for a single ...