<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".Download" android:orientation="vertical"> <Button android:id="@+id/download_StartButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="开始下载" /> <ProgressBar android:id="@+id/download_ProgressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="203dp" android:layout_height="40dp" /> <TextView android:id="@+id/download_ProgressTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center"/> <ImageView android:id="@+id/download_ImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center"/> </LinearLayout>
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
package com.example.drawableimgasynctask; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class Download extends Activity { private Button startButton; private ProgressBar downloadProgressBar; private TextView progressTextView; private ImageView downloadImageView; private final String mSource = "http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original/wYdFAUyCApeUbfWWP0YMsu6b4hs.jpg";// 源文件地址 private final String mPath = Environment.getExternalStorageDirectory() .toString() + "/imga.gif"; // 目标文件地址 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startButton = (Button) findViewById(R.id.download_StartButton); downloadProgressBar = (ProgressBar) findViewById(R.id.download_ProgressBar); progressTextView = (TextView) findViewById(R.id.download_ProgressTextView); downloadImageView = (ImageView) findViewById(R.id.download_ImageView); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new DownloadTask().execute(mSource, mPath); } }); } private class DownloadTask extends DownloadAsyncTask { @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int progress = values[0]; /* * 更新进度条和下载百分率 */ downloadProgressBar.setMax(size); downloadProgressBar.setProgress(progress); int percentage = progress * 100 / size; progressTextView.setText("已完成" + percentage + "%"); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (result) { Bitmap bitmap = BitmapFactory.decodeFile(mPath); downloadImageView.setImageBitmap(bitmap); } else { Toast.makeText(Download.this, "Error: " + errorMessage, 1000) .show(); } } } }
package com.example.drawableimgasynctask; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; 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 android.os.AsyncTask; public class DownloadAsyncTask extends AsyncTask<String, Integer, Boolean> { protected int size; protected String errorMessage; @Override protected Boolean doInBackground(String... params) { String url = params[0]; // 资源地址 String path = params[1]; // 目标路径 try { InputStream source = requestInputStream(url); // 请求源文件InputStream /** * 创建文件写入数据,并更新进度 */ fileWrite(source, path, new OnProgressUpdateListener() { @Override public void onProgressUpdate(int progress) { publishProgress(progress); } }); } catch (ClientProtocolException e) { errorMessage = e.getMessage(); cancel(true); return false; } catch (IOException e) { errorMessage = e.getMessage(); cancel(true); return false; } return true; } /** * 文件写入 * * @param in * 数据源输出流 * @param path * 文件路径 * @param listener * 下载进度监听器 * */ private void fileWrite(InputStream in, String path, OnProgressUpdateListener listener) throws IOException { File file = createFile(path); FileOutputStream fileOutputStream = new FileOutputStream(file); byte buffer[] = new byte[1024]; int progress = 0; int readBytes = 0; while ((readBytes = in.read(buffer)) != -1) { progress += readBytes; fileOutputStream.write(buffer, 0, readBytes); if (listener != null) { listener.onProgressUpdate(progress); } } in.close(); fileOutputStream.close(); } /** * 下载进度监听器 * */ private interface OnProgressUpdateListener { /** * 下载进度更新 * * @param progress * 进度 * */ public void onProgressUpdate(int progress); } /** * 根据资源URL地址取得资源输入流 * * @param url * URL地址 * @return 资源输入流 * @throws ClientProtocolException * @throws IOException * */ private InputStream requestInputStream(String url) throws ClientProtocolException, IOException { InputStream result = null; HttpGet httpGet = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpGet); int httpStatusCode = httpResponse.getStatusLine().getStatusCode(); if (httpStatusCode == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); size = (int) httpEntity.getContentLength(); result = httpEntity.getContent(); } return result; } /** * 根据文件路径创建文件 * * @param path * 文件路径 * @return 文件File实例 * @return IOException * */ private File createFile(String path) throws IOException { File file = new File(path); file.createNewFile(); return file; } /** * 返回错误信息 * * @return 错误信息 * */ public String getErrorString() { return this.errorMessage; } }
AsyncTask的3个泛型
• Param 传入数据类型
• Progress 更新UI数据类型
• Result 处理结果类型
AsyncTask的4个步骤
1、onPreExecute 执行前的操作
2、doInBackGround 后台执行的操作
3、onProgressUpdate 更新UI操作
4、onPostExecute 执行后的操作
从网络下载资源到SD卡的步骤:
1、HTTP请求资源InputStream
2、在SD中创建一个空文件
3、创建该文件的FileOutputStream
4、使用while循环,InputStream每次循环读入数据到字节数组buffer中(buffer字节数组的大小一般为1024的整数倍),FileOutputStream将buffer中的数据写入文件,直到EOF,read()方法返回-1
下载网络资源到本地
运行结果:
相关推荐
Android AsyncTask异步处理下载网页
Android AsyncTask的简单Demo,对应Blog文章:http://blog.csdn.net/dolacmeng/article/details/50215519
Android 使用AsyncTask异步更新UI界面
这个demo主要讲解了使用AsyncTask 异步下载网络图片,希望可以帮助需要的同学.
Android AsyncTask用法和异步加载图片通过AsyncTask 从网络上异步加载一张图片
AsyncTask 断点下载
Android AsyncTask Demo 自己参考网络写的学习 demo
1,实现android AsyncTask异步网络下载文件 2,AsyncTask的详细用法,有详细的注解 3,ProgressBar水平滚动条的动态实现方式,与正在下载文件的多少关联滚动条的进度多少。 4,可以中途取消下载文件
在Android中使用AsyncTask和Handler线程间交互的方式,详情参见博客:http://www.cnblogs.com/plokmju/p/android_AsyncTask.html和http://www.cnblogs.com/plokmju/p/android_Handler.html
AsyncTask的用法
Android Handler AsyncTask 异步加载
AsyncTask下载网络图片 进度条提示 大家看看啊
先申明啊,我这个小功能使用的下载地址是使用自己电脑上的Tomacat做的服务器,不会搭建服务器不会看代码的人不要在这里叫不能运行啊 // 给统一列表项的下载、停止、暂停、继续、进度条控件设置相同的Tag btn_...
Android_AsyncTask 关于AsyncTask 的一些常见应用。
详解Android中AsyncTask的使用。
Android中使用AsyncTask下载网页图片的代码清单.pdf 学习资料 复习资料 教学资源
Android开发之AsyncTask机制及使用细节例子源码 详见博客 http://www.cnblogs.com/samy/p/4217263.html
主要介绍了Android中异步类AsyncTask用法,分析总结了Async Task类的功能、特点及相关的使用技巧与注意事项,需要的朋友可以参考下
Android AsyncTask 同步下载图片,先是显示默认的图标,下载完成了立刻显示下载的图标,可以左右切换
AsyncTask下载网络图片 对话框提示 大家看看阿!