handler以及AnyscTask处理机制
1、Handler
主文件:MainActivity.java
package com.example.asynctaskdownload; import java.io.IOException; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity {
protected static final int SHOW_RESPONSE = 0;
/** Called when the activity is first created. */
private TextView textView;
private String result = ""; /////////////////////////////////////////////////////////
private Handler handler = new Handler(){ public void handleMessage(Message msg)
{
switch(msg.what){
case SHOW_RESPONSE:
String result = (String)msg.obj;
//注意是在此处进行UI操作
textView.setText(result);
}
}
};
/////////////////////////////////////////////////////
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
Button button = (Button) findViewById(R.id.readWebpage);
button.setOnClickListener(new OnClickListener()
{ @Override
public void onClick(View v) {
//
//textView.setText(result);
if(v.getId() == R.id.readWebpage)
{
sendRequestHttpUrl();
}
} });
}
////////////////////////////////////////////////////////
protected void sendRequestHttpUrl() {
// TODO Auto-generated method stub
//
new Thread(new Runnable()
{ @Override
public void run() {
// try
{
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://10.0.2.2:8080/mp3/a1.lrc"); HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
//关于此处中文乱码问题解决?文本文件保存时,文本文档默认为ANSI编码格式,另存为时手动改为utf-8格式即可
result = EntityUtils.toString(entity, "utf-8");
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = result.toString();
handler.sendMessage(message);
}catch(Exception ex)
{
ex.printStackTrace();
} } }
).start();
}
}
activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:id="@+id/readWebpage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Load Webpage" >
</Button>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/TextView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Placeholder" >
</TextView>
</ScrollView> </LinearLayout>
运行结果:

2、AnyscTask
主代码:
package com.example.asynctaskdownload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity {
private TextView textView; private final String fileName = "a1.lrc";
//private final String fileUrl = "http://10.0.2.2:8080/mp3/a1.lrc";
private int result = Activity.RESULT_CANCELED;
private String response = ""; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
Button button = (Button) findViewById(R.id.readWebpage);
button.setOnClickListener(new OnClickListener()
{ @Override
public void onClick(View v) {
// DownloadWebPageTask task = new DownloadWebPageTask();
//task.execute(new String[] { "http://www.vogella.com" });
task.execute(new String[] { "http://10.0.2.2:8080/mp3/a1.lrc" });
Toast.makeText(MainActivity.this, "Download Success!", Toast.LENGTH_LONG).show(); // textView.setText(response);
} });
} private class DownloadWebPageTask extends AsyncTask<String, Void, Integer> {
@Override
protected Integer doInBackground(String... urls) {
//获取sdcard的路径,以及设置保存的文件名
File output = new File(Environment.getExternalStorageDirectory(), fileName);
if(output.exists())
{
output.delete();//若同名文件已存在则删除
} // String response = "";
InputStream content = null;
FileOutputStream fos = null;
//遍历url数组中的url,采用HttpClient(接口)的方式访问网络
for (String url : urls) {
//首先创建一个DefaultHttpClient实例
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);//发起一个GET请求,创建一个HttpGet对象,并传入目标网络地址
try {
HttpResponse execute = client.execute(httpGet);//调用execute执行访问请求并返回一个HttpResponse对象
if(execute.getStatusLine().getStatusCode() == 200)
{
//注:下面两行code只能使用其中一个:content will be consume only once
//execute.getEntity()调用了两次
// content = execute.getEntity().getContent();//获取服务返回的具体内容
//调用EntityUtils.toString该静态方法将HttpEntity转换成字符串,为避免中文字符乱码,添加utf-8字符集参数
// response = EntityUtils.toString(execute.getEntity(), "utf-8");
//////////////////////////////////////////////////////////////////////////////
HttpEntity entity = execute.getEntity();
// response = EntityUtils.toString(entity, "utf-8");
content = entity.getContent(); } //利用管道 inputstream-->reader
InputStreamReader reader = new InputStreamReader(content);
fos = new FileOutputStream(output.getPath()); int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
} result = Activity.RESULT_OK; // BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); // String s = "";
// while ((s = buffer.readLine()) != null) {
// response += s;
// } } catch (Exception e) {
e.printStackTrace();
}finally {
if (content != null) {
try {
content.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return result;
} protected void onPostExecute(Integer result) {
//此处可以根据后台任务完成后返回的结果进行一些UI操作 if(result == Activity.RESULT_OK)
{
textView.setText("mp3 file download success!!");
}
} /* public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
//task.execute(new String[] { "http://www.vogella.com" });
task.execute(new String[] { "http://10.0.2.2:8080/mp3/a1.lrc" }); }*/ }
}
activity_main.xml文件同上
运行结果:成功下载文件a1.lrc到sdcard中
handler以及AnyscTask处理机制的更多相关文章
- Android正在使用Handler实现信息发布机制(一)
上一篇文章,我们谈到了电话Handler的sendMessage方法,最后,我们将进入一个电话 sendMessageAtTime方法,例如下列: public boolean sendMessage ...
- Android正在使用Handler实现消息分发机制(零)
演讲前,AsyncTask文章.我们在最后谈到.AsyncTask它是利用Handler异步消息处理机制,操作结果.使用Message回到主线程,从而执行UI更新线程. 而在我们的日常开发工作,Han ...
- Android Handler MessageQueue Looper 消息机制原理
提到Android里的消息机制,便会提到Message.Handler.Looper.MessageQueue这四个类,我先简单介绍以下这4个类 之间的爱恨情仇. Message 消息的封装类,里边存 ...
- Android正在使用Handler实现消息分发机制(两)
在开始这篇文章之前,.首先,我们在总结前两篇文章Handler, Looper和MessageQueue像一些关键点: 0)在创建线程Handler之前,你必须调用Looper.prepare(), ...
- android的消息处理机制——Looper,Handler,Message
在开始讨论android的消息处理机制前,先来谈谈一些基本相关的术语. 通信的同步(Synchronous):指向客户端发送请求后,必须要在服务端有回应后客户端才继续发送其它的请求,所以这时所有请求将 ...
- Android多线程机制和Handler的使用
参考教程:iMooc关于Handler,http://www.imooc.com/learn/267 参考资料:Google提供Android文档Communicating with the UI T ...
- Android Handler处理机制 ( 一 )(图+源码分析)——Handler,Message,Looper,MessageQueue
android的消息处理机制(图+源码分析)——Looper,Handler,Message 作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习 google大牛们的设计思想. ...
- Android的消息处理机制Looper,Handler,Message
android的消息处理有三个核心类:Looper,Handler和Message.其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道,因 ...
- 转 Android的消息处理机制(图+源码分析)——Looper,Handler,Message
作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习google大牛们的设计思想.android源码中包含了大量的设计模式,除此以外,android sdk还精心为我们设计了各种 ...
随机推荐
- linix container & cgroup note
1,Containers can run instructions native to the core CPU without any special interpretation mechanis ...
- Java基础之集合框架——使用集合Vector<>挑选演员(TryVector)
控制台程序. public class Person implements Comparable<Person> { // Constructor public Person(String ...
- IntelliJ IDEA 显示行号方法
设置方法如下: File->Settings->Editor->General->Appearence->Show Line Number
- linux 命令之 insmod
man insmod: INSMOD(8) insmod INSMOD(8) NAME insmod - Simple program to insert a module into the Linu ...
- Swift实战-豆瓣电台(二)界面布局
观看地址 http://v.youku.com/v_show/id_XNzMwMDg4NzAw.html 这节的内容主要是storyboard的操作. 有以下几个知识点 1 TableView的Dat ...
- 汉字转【pinyin】
引言 github地址:aizuyan/pinyin 无意中看到了overtrue/pinyin这个项目,感觉很有意思,这个项目做了这么一件事情: 将汉字转化为拼音 刚看到这里是不是觉得没什么难度,没 ...
- HUD 5086 Revenge of Segment Tree(递推)
http://acm.hdu.edu.cn/showproblem.php?pid=5086 题目大意: 给定一个序列,求这个序列的子序列的和,再求所有子序列总和,这些子序列是连续的.去题目给的第二组 ...
- poj 题目分类(1)
poj 题目分类 按照ac的代码长度分类(主要参考最短代码和自己写的代码) 短代码:0.01K--0.50K:中短代码:0.51K--1.00K:中等代码量:1.01K--2.00K:长代码:2.01 ...
- C++多线程调试和测试的注意事项
在一个程序中,这些独立运行的程序片断叫作“线程”(Thread),利用它编程的概念就叫作“多线程处理”.利用线程,用户可按下一个按钮,然后程序会立即作出响应,而不是让用户等待程序完成了当前任务以后才开 ...
- Codeforces Beta Round #93 (Div. 1 Only) D. Fibonacci Sums
先考虑一个斐波那契数能分成其他斐波那契数的方案,假如f[i]表示第i个斐波那契数,那么只要对他进行拆分,f[i-1]这个数字必定会存在.知道这一点就可以进行递推了.先将数字分成最少项的斐波那契数之和, ...