为简单而努力:Android封装类详解
一、简单说明
1, IntentService
IntentService继承自Service,并在其内部创建了工作线程,用来处理耗时操作,其中onHandleIntent方法就是在子线程执行的,我们可以在这里处理耗时操作。
启动时与正常service一样,可以调用startservice来启动IntentService。
注意:(1),在无参构造函数里,必须调用父类一个参数的构造方法; (2),与普通服务不同,IntentService的子线程处理完耗时操作,服务便销毁。
2, HandlerThread
HandlerThread 继承自Thread, 本质上就是一个Thread,内部封装了Looper,不用我们再处理Looper的初始化与消息循环。
我们可以通过获取HandlerThread 内部的looper来构建一个子线程的handler,从而与主线程交互。
常见使用方法:
// 1,创建handlerThread并启动该线程
		HandlerThread MyThread = new HandlerThread("MyThread");
		MyThread.start();
//2,获取子线程的looper
Looper looper = MyThread.getLooper();
//3,通过子线程的looper创建handler,从而该handler便与子线程绑定
		handler = new Handler(looper);
		handler#doSomeThing...
3, AsyncQueryHandler
异步查询类,常见使用方法:
//1,继承AsyncQueryHandler并重写onXXXComplete方法,以便增删改查等操作执行完毕后进行下一步操作。
private static class QueryHandler extends AsyncQueryHandler {
public QueryHandler(ContentResolver cr) {
			super(cr);
		}
@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			super.onQueryComplete(token, cookie, cursor);
			System.out.println("查询完毕: " + System.currentTimeMillis());
		}
}
//2,调用startXXX方法执行增删改查操作
Uri uri = Sms.CONTENT_URI;
		QueryHandler mQueryHandler = new QueryHandler(getContentResolver());
		mQueryHandler.startQuery(100, "cookie", uri, null, null, null, Sms.DEFAULT_SORT_ORDER);
4, Loader
主要用来异步加载数据,常见的有AsyncLoader, CursorLoader,详情请参考:Android Loader使用详解
5, AsyncTask
异步任务类,常见,不再赘述
二、代码Demo
//java code
package com.wytiger.goodclass;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.SystemClock;
import android.provider.Telephony.Sms;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
protected static final String TAG = "MainActivity";
	private int count = 0;
	private Handler handler;
@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
		Button button2 = (Button) findViewById(R.id.button2);
		Button button3 = (Button) findViewById(R.id.button3);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
	}
@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			// 启动MyIntentService
			startService(new Intent(this, MyIntentService.class));
			Toast.makeText(this, "点击IntentService", 0).show();
			break;
		case R.id.button2:
			testHandlerThread();
			Toast.makeText(this, "点击HandlerThread", 0).show();
			break;
		case R.id.button3:
			startQuery();
			Toast.makeText(this, "点击AsyncQueryHandler", 0).show();
			break;
default:
			break;
		}
}
private void testHandlerThread() {
		// 创建handlerThread
		HandlerThread MyThread = new HandlerThread("MyThread");
		MyThread.start();
		System.out.println("当前线程:" + Thread.currentThread().getName());
		System.out.println("handler线程:" + MyThread.getName());
Looper looper = MyThread.getLooper();
		// 子线程的handler
		handler = new Handler(looper);
		handler.post(mRunnable);
	}
/**
	 * 这在子线程执行
	 */
	private Runnable mRunnable = new Runnable() {
public void run() {
			count++;
			// 为了方便 查看,我们用Log打印出来
			Log.e(TAG, Thread.currentThread().getName() + ": " + count);
			SystemClock.sleep(1000);
			// 每2秒执行一次
			handler.post(mRunnable);
		}
};
@TargetApi(Build.VERSION_CODES.KITKAT)
	private void startQuery() {
		Uri uri = Sms.CONTENT_URI;
		QueryHandler mQueryHandler = new QueryHandler(getContentResolver());
		mQueryHandler.startQuery(100, "cookie", uri, null, null, null, Sms.DEFAULT_SORT_ORDER);
		System.out.println("开始查询: " + System.currentTimeMillis());
	}
/**
	 * 异步查询类
	 * 
	 * @author wytiger
	 * @date 2016-5-26
	 */
	private static class QueryHandler extends AsyncQueryHandler {
public QueryHandler(ContentResolver cr) {
			super(cr);
		}
@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			super.onQueryComplete(token, cookie, cursor);
			System.out.println("查询完毕: " + System.currentTimeMillis());
		}
@Override
		protected void onInsertComplete(int token, Object cookie, Uri uri) {
			super.onInsertComplete(token, cookie, uri);
		}
@Override
		protected void onUpdateComplete(int token, Object cookie, int result) {
			super.onUpdateComplete(token, cookie, result);
		}
@Override
		protected void onDeleteComplete(int token, Object cookie, int result) {
			super.onDeleteComplete(token, cookie, result);
		}
}
@Override
	protected void onDestroy() {
		super.onDestroy();
		handler.removeCallbacksAndMessages(mRunnable);
	}
}
//xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
<Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="IntentService" />
<Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="HandlerThread" />
<Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="AsyncQueryHandler" />
<Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Loader" />
     <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="AsyncTask" />
</LinearLayout>
//权限声明
<uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
为简单而努力:Android封装类详解的更多相关文章
- Android Notification 详解(一)——基本操作
		
Android Notification 详解(一)--基本操作 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Notification 文中如有纰 ...
 - Android Notification 详解——基本操作
		
Android Notification 详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 前几天项目中有用到 Android 通知相关的内容,索性把 Android Notificatio ...
 - Android ActionBar详解
		
Android ActionBar详解 分类: Android2014-04-30 15:23 1094人阅读 评论(0) 收藏 举报 androidActionBar 目录(?)[+] 第4 ...
 - Android编译系统详解(一)
		
++++++++++++++++++++++++++++++++++++++++++ 本文系本站原创,欢迎转载! 转载请注明出处: http://blog.csdn.net/mr_raptor/art ...
 - Android布局详解之一:FrameLayout
		
原创文章,如有转载,请注明出处:http://blog.csdn.net/yihui823/article/details/6702273 FrameLayout是最简单的布局了.所有放在布局里的 ...
 - 【整理修订】Android.mk详解
		
Android.mk详解 1. Android.mk 的应用范围 Android.mk文件是GNU Makefile的一小部分,它用来对Android程序进行编译. 一个Android.mk文件可以编 ...
 - Android签名详解(debug和release)
		
Android签名详解(debug和release) 1. 为什么要签名 1) 发送者的身份认证 由于开发商可能通过使用相同的Package Name来混淆替换已经安装的程序,以此保证签名不同的包 ...
 - Android菜单详解(一)——理解android中的Menu
		
前言 今天看了pro android 3中menu这一章,对Android的整个menu体系有了进一步的了解,故整理下笔记与大家分享. PS:强烈推荐<Pro Android 3>,是我至 ...
 - 【转】Android菜单详解——理解android中的Menu--不错
		
原文网址:http://www.cnblogs.com/qingblog/archive/2012/06/08/2541709.html 前言 今天看了pro android 3中menu这一章,对A ...
 
随机推荐
- [No000017]单词拼写记不住?试试这俩方法-单词拼写,怎么记又快又好?
 - BZOJ 2724: [Violet 6]蒲公英
			
2724: [Violet 6]蒲公英 Time Limit: 40 Sec Memory Limit: 512 MBSubmit: 1633 Solved: 563[Submit][Status ...
 - AngularJs 时间格式化处理
			
1.AngularJs的controller中格式: var dateAsString = $filter('date')(item_date, "yyyy-MM-dd hh:mm:ss&q ...
 - datepicker monthpicker
 - 搜索引擎关键词劫持之php篇(源码与分析)
			
摘要:其实原理很简单: 搜索引擎关键词劫持的过程实际上就是,修改肉鸡站点(webshell站点)A的首页(希望被搜索引擎收录的页面,一般情况下是首页),使之做出如下判断: if(来访者是蜘蛛){ 输出 ...
 - C# Winform应用程序占用内存较大解决方法整理(转)
			
原文:http://www.jb51.net/article/56682.htm 背景: 微软的 .NET FRAMEWORK 现在可谓如火如荼了.但是,.NET 一直所为人诟病的就是“胃口太大”,狂 ...
 - Nodejs生态圈的TypeScript+React
			
基于Nodejs生态圈的TypeScript+React开发入门教程 基于Nodejs生态圈的TypeScript+React开发入门教程 概述 本教程旨在为基于Nodejs npm生态圈的前端程 ...
 - QT 数据库编程四
			
//vmysql.cpp #include "vmysql.h" #include <QMessageBox> Vmysql::Vmysql() { mysql_ini ...
 - Centos 7 安装jdk 配置环境变量
			
在Centos7 终端中,我们输入java -version可以看到java的版本,但是输入javac却没有反应 原因是系统中预装的是openjdk jre不是真正的jdk,所以还得自己装好,然后配置 ...
 - mac上如何卸载oracle jdk 1.7
			
目前mac上有一些软件还不支持jdk1.7,只能卸载1.7,恢复到1.6,下面二个链接是官网给出的卸载方法: http://www.java.com/zh_CN/download/help/mac_u ...