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还精心为我们设计了各种 ...
随机推荐
- [Intellij IDEA]File size exceeds configured limit(2560000). Code insight features are not available
在使用 IDEA, 发现一个问题File size exceeds configured limit (2560000). Code insight features not available.
- 遇到could not find developer disk image 问题怎么解决
一般是设备的版本低于或者高于当前的xcode
- 最长上升子序列的变形(N*log(N))hdu5256
序列变换 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- With as 递归查询
use TEST create table Provinces ( pro_Id ,), pro_Name nvarchar(), pro_Code nvarchar(), pro_PId int ) ...
- fzu 2146 Easy Game
http://acm.fzu.edu.cn/problem.php?pid=2146 Problem 2146 Easy Game Accept: 661 Submit: 915Time Li ...
- C++之路进阶——bzoj1823(满汉全席)
F.A.Qs Home Discuss ProblemSet Status Ranklist Contest ModifyUser hyxzc Logout 捐赠本站 Notice:由于本OJ建立在 ...
- Codeforces Round #312 (Div. 2) E. A Simple Task
题目大意就是给一个字符串,然后多个操作,每次操作可以把每一段区间的字符进行升序或者降序排序,问最终的字符串是多少. 一开始只考虑字符串中字符'a'的情况,假设操作区间[L,R]中有x个'a',那么一次 ...
- 夺命雷公狗---微信开发17----自定义菜单的事件推送,响应菜单的CLICK
废话不多说,index.php 代码如下所示: <?php /** * wechat php test */ //define your token require_once "com ...
- stdlib 头文件
stdlib 头文件即standard library标准库头文件.stdlib.h里面定义了五种类型.一些宏和通用工具函数. 类型例如size_t.wchar_t.div_t.ldiv_t和lldi ...
- switch结构2016/03/08
Switch 03/08 一.结构 switch(){ case *: ;break;……default: ;brek;} 练习:输入一个日期,判断这一年第几天? Console.Write(&q ...