• Android中设置进度条来监督下载进程


    昨天做了一个Android中利用进度条来监督下载一个图片或者一首歌曲的进度:

    简单的界面,但是可以实现那个功能:

    这是main.xml中的代码:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

     <TextView
         android:id="@+id/txt"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#FFFF37"
            android:text="下载进度" />

        <Button
            android:id="@+id/downImg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_style"
            android:text="开始下载图片" />

        <FrameLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <ImageView
                android:id="@+id/imgView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/app_name" />

            <ProgressBar
                android:id="@+id/progressBar"
                android:layout_width="fill_parent"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:visibility="invisible" />
        </FrameLayout>


    </LinearLayout>

    这里是drawable里面去实现button点击的按钮样式的:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
            <item android:state_pressed="true">
            <shape>
                <gradient android:startColor="#0d76e1" android:endColor="#0d76e1"
                    android:angle="270" />
                <stroke android:width="1dip" android:color="#f403c9" />
                <corners android:radius="2dp" />
                <padding android:left="10dp" android:top="10dp"
                    android:right="10dp" android:bottom="10dp" />
            </shape>
        </item>
     
        <item android:state_focused="true">
            <shape>
                <gradient android:startColor="#ffc2b7" android:endColor="#ffc2b7"
                    android:angle="270" />
                <stroke android:width="1dip" android:color="#f403c9" />
                <corners android:radius="2dp" />
                <padding android:left="10dp" android:top="10dp"
                    android:right="10dp" android:bottom="10dp" />
            </shape>
        </item>
     
        <item>
            <shape>
                <gradient android:startColor="#000000" android:endColor="#ffffff"
                    android:angle="180" />
                <stroke android:width="1dip" android:color="#f403c9" />
                <corners android:radius="5dip" />
                <padding android:left="10dp" android:top="10dp"
                    android:right="10dp" android:bottom="10dp" />
            </shape>
        </item>

    </selector>

    接下来的这个就是实现其功能的主要代码:.java文件

    package cn.android.app.hsd;

    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.ProgressBar;
    import android.widget.TextView;

    public class Chapter_11_URL_exampleActivity extends Activity implements OnClickListener { 
     // 声明视图上的各个对象
     private TextView txtView;
     private Button downImg;
     private ImageView imgView;
     // 定义一个ProgressBar控件,用于显示下载的进度
     private ProgressBar progressBar;
     private Bitmap bitmap;
     // 定义下载任务的状态,下载中,下载完成
     private static final int LOADING = 1;
     private static final int END = 2;
     //初始化进度条的最大值和最小值
     int maxSize = 0;
     int nowSize = 0;

     Handler handler;
     // 把图片写入到sd卡中,所以这里我们要定义一个路径

     private static final String SDCARD = "mnt/sdcard/";
     private String fileName = "networkImg.jpg";

    //声明一个文件,待会用于存储
     File file;
     //设置图片的url,这里的url是在网上随便找到一张图片,然后点击起链接
      String imgHttp1 = "http://c.hiphotos.baidu.com/image/w%3D2048/sign=f1e49b68aa64034f0fcdc5069bfb7831/060828381f30e9240286c9844d086e061d95f761.jpg";
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

    //然后将这些控件都实例化

      txtView = (TextView) findViewById(R.id.txt);
      downImg = (Button) findViewById(R.id.downImg);

    //将按钮控件实现监听

      downImg.setOnClickListener(this);
      imgView = (ImageView) findViewById(R.id.imgView);
      progressBar = (ProgressBar) findViewById(R.id.progressBar);

    //注意这里我们要涉及到更新ui界面,我们不能直接去更新,这就是java与android的区别,所以,我们要记住用handler

      handler = new Handler() {
       @Override
       public void handleMessage(Message msg) {
        if (null != progressBar) {
         // 设置进度条最大值
         progressBar.setMax(maxSize);
         // 当前已经下载的值
         nowSize += msg.getData().getInt("loadingSize");
         // 设置进度条的当前进度值
         progressBar.setProgress(nowSize);
         if (msg.what == LOADING) {
          // 显示已经下载的值(这里会有一点计算)
          txtView.setText("已下载:" + (nowSize*100)/maxSize  + "%");

          Log.e("Chapter_11_URL_exampleActivity", "正在下载:"+ nowSize);
         }

         if (msg.what == END) {
          // 下载完成后隐藏进度条
          progressBar.setVisibility(View.INVISIBLE);
          // 显示图片
          imgView.setImageBitmap(bitmap);
          // 将图片保存到sdcard中
          saveImg(SDCARD + fileName, bitmap);
          // 结束当前线程
          Thread.currentThread().interrupt();
         }
        }
       }
      };
     }

    //实现其点击事件

     @Override
     public void onClick(View paramView) {
      // 首先清空图片和进度条
      if (null != bitmap) {
       imgView.setImageBitmap(null);
       nowSize = 0;
       progressBar.setProgress(0);
       txtView.setText("即将下载......");
      }

      // 1、显示进度条
      progressBar.setVisibility(View.VISIBLE);

      // 2、开始下载
      new MyThread(imgHttp1).start();
     }

     // 保存图片方法
     public void saveImg(String fullPath, Bitmap bitmap) {
      File file = new File(fullPath);
      if (file.exists()) {
       file.delete();
      } else if (!file.exists()) {
       try {
        file.createNewFile();
       } catch (IOException e) {
        e.printStackTrace();
       }
      }

      try {
       FileOutputStream fos = new FileOutputStream(file);
       boolean isSaved = bitmap.compress(Bitmap.CompressFormat.JPEG, 100,fos);

       if (isSaved) {
        fos.flush();
        fos.close();
       }
       System.out.println("文件保存成功!");
      } catch (FileNotFoundException e) {
       System.out.println("保存失败(FileNotFoundException)");
       e.printStackTrace();
      } catch (IOException e) {
       System.out.println("保存失败(IOException)");
       e.printStackTrace();
      }

     }

     class MyThread extends Thread {  
      String httpImg;
      //定义构造方法用来接收图片
      public MyThread(String httpImg) {
       this.httpImg = httpImg;
      }

      @Override
      public void run() {
       //(字节数组流)捕获内存缓冲区的数据,转换成字节数组
       ByteArrayOutputStream bos = new ByteArrayOutputStream();

       try {
        // 实例化URL对象,指定资源(图片)下载的地址
        URL url = new URL(httpImg);
        HttpURLConnection con = (HttpURLConnection) url
          .openConnection();
        con.setDoInput(true);
        con.connect();
        InputStream is = con.getInputStream();

        // 获取文件的大小
        maxSize = con.getContentLength();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
         bos.write(buffer, 0, len);
         bos.flush();
         // 发送消息
         Message msg = new Message();
         msg.what = LOADING;
         Bundle bundle = new Bundle();
         bundle.putInt("loadingSize", len);
         msg.setData(bundle);
         Thread.sleep(1);//方法休眠20
         handler.sendMessage(msg);
        }

        // 关闭输入流
        is.close();
        // 关闭连接
        con.disconnect();

        byte[] imgBytes = bos.toByteArray();
        bitmap = BitmapFactory.decodeByteArray(imgBytes, 0,imgBytes.length);

        // 下载结束后发送消息
        Message msg = new Message();
        msg.what = END;
        handler.sendMessage(msg);
       } catch (MalformedURLException e) {
        e.printStackTrace();
       } catch (IOException e) {
        e.printStackTrace();
       } catch (InterruptedException e) {
        e.printStackTrace();
       }
      }
     }
     
    }

    一切只是为了充实自己!!stay hungry and stay foolish!!
  • 相关阅读:
    贪心算法过河问题 pojo1700
    大脑的合理使用
    给自己的忠言
    篮子水果模拟消费者生产者
    线程安全高效的单例模式
    Java提高篇——JVM加载class文件的原理机制
    递归的研究
    虚拟机分区方法
    使用spark dataSet 和rdd 解决 某个用户在某个地点待了多长时间
    获取数据集的好的方
  • 原文地址:https://www.cnblogs.com/Catherine-Brain/p/3475477.html
Copyright © 2020-2023  润新知