运用AsyncTask下载图片并显示下载进度,下载完成后显示

执行主窗体的代码:

public class MainActivity extends AppCompatActivity {
    //下载图片的url
    private String url = "http://p4.so.qhmsg.com/t01ba3531d5c8665a69.jpg";
    private ImageView ivPicOne;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ivPicOne = (ImageView) findViewById(R.id.ivPicOne);
    }
    
    public void download(View view){
	//通过点击按钮启动AsyncTask
        new MyAsyncTask(ivPicOne,this).execute(url);
    }
}
这段代码很简单,主要就是一个通过点击按钮来启动AsyncTask进行下载任务;

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.shen.fourth.MainActivity">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ivPicOne"
        android:src="@mipmap/ic_launcher"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="download"
        android:onClick="download"/>
</LinearLayout>
线性布局里放置了一个ImageView用来显示下载的图片,一个按钮用来启动AsyncTask;


主要代码在AsyncTask自定义类里面:

public class MyAsyncTask extends AsyncTask <String,Integer,Bitmap>{
    private ImageView ivPicOne;	
    //进度条对话框,用来显示进度
    private ProgressDialog dialog;
    private Context context;

    public MyAsyncTask(ImageView ivPicOne, Context context) {
        this.ivPicOne = ivPicOne;
        this.context = context;
    }
    //2.执行耗时操作,子线程
    @Override
    protected Bitmap doInBackground(String... strings) {
        HttpURLConnection conn = null;
        InputStream is = null;
        try {
            URL url = new URL(strings[0]);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(1000);
            conn.connect();
            if(conn.getResponseCode() == 200){
                is = conn.getInputStream();
                byte[] buff = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int len = 0;
		//currentSize变量用来统计当前已经下载的数据的总大小
                int currentSize = 0;
		//totalSize变量用来获得将要下载图片的总大小
                int totalSize = conn.getContentLength();
                while((len = is.read(buff))!=-1){
		    //累加
                    currentSize += len;
		    //算出百分比
                    int progressSize = (int)(currentSize/(double)totalSize * 100);
		    //Log面板显示当前进度
                    Log.i("progressSize+++++++++",progressSize+"");
   		    //更新进度
                    publishProgress(progressSize);
                    baos.write(buff,0,len);
                    baos.flush();
                }
                byte[] datas = baos.toByteArray();
                baos.close();
                Bitmap bitmap = BitmapFactory.decodeByteArray(datas,0, datas.length);
                return bitmap;



            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //1.作一些准备工作,UI主线程
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
	//创建进度条对话框
        dialog = new ProgressDialog(context);
	//设置对话框的属性
        dialog.setTitle("提示");
        dialog.setIcon(R.mipmap.ic_launcher);
        dialog.setMessage("正在下载中。。。");
	//设置为水平进度条
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	//显示
        dialog.show();


    }
 
   
     //3.耗时操作执行完执行此方法,用于更新UI,UI主线程
@Override protected void onPostExecute(Bitmap bitmap) {
	//绑定图片信息
        ivPicOne.setImageBitmap(bitmap);
	//关闭进度条对话框
        dialog.dismiss();
        super.onPostExecute(bitmap);
    }
    
    //该方法会在执行耗时操作过程中多次被调用
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
	//更新进度对话框中的进度值
        dialog.setProgress(values[0]);
    }
}
ok,完毕~欢迎大家讨论交流



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AsyncTask下载视频的步骤如下: 1. 在 doInBackground() 方法中执行网络请求,获取视频数据并存储到本地文件中。 ```java @Override protected String doInBackground(String... urls) { String url = urls[0]; try { URL videoUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) videoUrl.openConnection(); connection.connect(); // 获取视频文件长度 int length = connection.getContentLength(); // 创建输入流 InputStream input = new BufferedInputStream(connection.getInputStream()); // 创建输出流 OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/video.mp4"); byte[] data = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; // 计算进度 int progress = (int) ((total * 100) / length); publishProgress(progress); // 写入文件 output.write(data, 0, count); } // 关闭流 output.flush(); output.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } return null; } ``` 2. 在 onProgressUpdate() 方法中更新下载进度。 ```java @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int progress = values[0]; // 更新进度条 progressBar.setProgress(progress); } ``` 3. 在 onPostExecute() 方法中通知用户下载完成。 ```java @Override protected void onPostExecute(String s) { super.onPostExecute(s); // 下载完成 Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show(); } ``` 完整的 AsyncTask 下载视频的代码如下: ```java public class DownloadVideoTask extends AsyncTask<String, Integer, String> { private Context context; private ProgressBar progressBar; public DownloadVideoTask(Context context, ProgressBar progressBar) { this.context = context; this.progressBar = progressBar; } @Override protected String doInBackground(String... urls) { String url = urls[0]; try { URL videoUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) videoUrl.openConnection(); connection.connect(); // 获取视频文件长度 int length = connection.getContentLength(); // 创建输入流 InputStream input = new BufferedInputStream(connection.getInputStream()); // 创建输出流 OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/video.mp4"); byte[] data = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; // 计算进度 int progress = (int) ((total * 100) / length); publishProgress(progress); // 写入文件 output.write(data, 0, count); } // 关闭流 output.flush(); output.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int progress = values[0]; // 更新进度条 progressBar.setProgress(progress); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); // 下载完成 Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show(); } } ``` 使用方法如下: ```java ProgressBar progressBar = findViewById(R.id.progress_bar); DownloadVideoTask task = new DownloadVideoTask(this, progressBar); task.execute("http://www.example.com/video.mp4"); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值