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处理机制的更多相关文章

  1. Android正在使用Handler实现信息发布机制(一)

    上一篇文章,我们谈到了电话Handler的sendMessage方法,最后,我们将进入一个电话 sendMessageAtTime方法,例如下列: public boolean sendMessage ...

  2. Android正在使用Handler实现消息分发机制(零)

    演讲前,AsyncTask文章.我们在最后谈到.AsyncTask它是利用Handler异步消息处理机制,操作结果.使用Message回到主线程,从而执行UI更新线程. 而在我们的日常开发工作,Han ...

  3. Android Handler MessageQueue Looper 消息机制原理

    提到Android里的消息机制,便会提到Message.Handler.Looper.MessageQueue这四个类,我先简单介绍以下这4个类 之间的爱恨情仇. Message 消息的封装类,里边存 ...

  4. Android正在使用Handler实现消息分发机制(两)

    在开始这篇文章之前,.首先,我们在总结前两篇文章Handler, Looper和MessageQueue像一些关键点: 0)在创建线程Handler之前,你必须调用Looper.prepare(), ...

  5. android的消息处理机制——Looper,Handler,Message

    在开始讨论android的消息处理机制前,先来谈谈一些基本相关的术语. 通信的同步(Synchronous):指向客户端发送请求后,必须要在服务端有回应后客户端才继续发送其它的请求,所以这时所有请求将 ...

  6. Android多线程机制和Handler的使用

    参考教程:iMooc关于Handler,http://www.imooc.com/learn/267 参考资料:Google提供Android文档Communicating with the UI T ...

  7. Android Handler处理机制 ( 一 )(图+源码分析)——Handler,Message,Looper,MessageQueue

    android的消息处理机制(图+源码分析)——Looper,Handler,Message 作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习 google大牛们的设计思想. ...

  8. Android的消息处理机制Looper,Handler,Message

    android的消息处理有三个核心类:Looper,Handler和Message.其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道,因 ...

  9. 转 Android的消息处理机制(图+源码分析)——Looper,Handler,Message

    作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习google大牛们的设计思想.android源码中包含了大量的设计模式,除此以外,android sdk还精心为我们设计了各种 ...

随机推荐

  1. java中DriverManager跟DataSource获取getConnection有什么不同?

    1.datasource是与连接池获取连接,而DriverManager是获取与数据库的连接! DriverManager类的主要作用是管理注册到DriverManager中的JDBC驱动程序,并根据 ...

  2. Azure billing 分析(2)

    美国中南部的2008R2的A1的VM放了一天,CPU时间涨了13个小时,有点小贵,真的没有操作啊... 提示早上7到9点有一个小高峰. 看来平时没什么访问量时,还是改成A0能省点钱.因为第一天是用A0 ...

  3. 设置UISegmentedControl中字体大小

    [segmentedControl setTitleTextAttributes:@{NSFontAttributeName : DYBoldFont(20)}  forState:UIControl ...

  4. PostgreSQL pg_dump pg_dumpall and restore

    pg_dump dumps a database as a text file or to other formats. Usage: pg_dump [OPTION]... [DBNAME] Gen ...

  5. 20145207 《Java程序设计》第二周学习总结

    开源中国的代码托管 不算调查问卷的话,这是第二篇博客,怎么说呢……感觉好麻烦!哈哈哈哈!不过也就这样吧.按照同学传达的老师的意思就是“写博客就是在重复一天的所学,虽然可能会花一定的时间,但是对于自己是 ...

  6. CS2013调试DLL

    需要打开两个项目,一个是Win32Project1,由这个项目创建DLL,注意要在DLL函数前加上__declspec(dllexport),这样就会还配套生成一个.lib 然后再打开一个项目,一般为 ...

  7. 1019: A+B和C比大小

    1019: A+B和C比大小 时间限制: 1 Sec  内存限制: 128 MB提交: 518  解决: 300[提交][状态][讨论版] 题目描述 给定区间[-231, 231]内的3个整数A.B和 ...

  8. full_case & parallel_case

    case中的full_case与parallel_case讨论: 1)术语介绍: 整个case模块叫做:case_statement,注释部分叫做case_statement_header case ...

  9. android模拟器启动没有拨号功能

    网上查询了很多资料, 其中一位网友给出的结论是android 4.3模拟器的bug, 如果在通讯录中添加好友,也是可以进行拨号的. 总结: 自认为是SDK安装程序不完整或设置AVD模拟器的时候设置项出 ...

  10. json_encode注意

    PHP5.2或以上的版本把json_encode作为内置函数来用,但只支持utf-8编码的字符,否则中文就会出现乱码或者空值.解决办法如下: 1.保证在使用JSON处理的时候字符是以UTF8编码的.具 ...