Android文件预告之进度检测
2016-02-28 11:40:14 | 来源:玩转帮会 | 投稿:佚名 | 编辑:dations

原标题:Android文件预告之进度检测

近期因为项目的需要,研究了一下Android文件预告进度显示的功能实现,接下来就和大家一起分享学习一下,希望对广大初学者有帮助。先上效果图:

上方的蓝色进度条,会根据文件预告量的百分比进行加载,中部的文本控件用来现在文件预告的百分比,最下方的ImageView用来展示预告好的文件,项目的目的就是动态向用户展示文件的预告量。

下面看代码实现:首先是布局文件:

<RelativeLayout 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"
    tools:context="${relativePackage}.${activityClass}" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progressBar"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp"
        android:text="TextView" />
    <ImageView
        android:id="@+id/imageView"
        android:layout_marginTop="24dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_below="@+id/textView"
        android:contentDescription="@string/app_name"
        android:src="@drawable/ic_launcher" />
</RelativeLayout>

接下来的主Activity代码:

public class MainActivity extends Activity {
	ProgressBar pb;   
	TextView tv; 
	ImageView imageView;
    int fileSize;    
    int downLoadFileSize;    
    String fileEx,fileNa,filename;  
    //用来接收线程发送来的文件预告量,进行UI界面的更新
    private Handler handler = new Handler(){    
        @Override    
        public void handleMessage(Message msg)    
        {//定义一个Handler,用于处理预告线程与UI间通讯
          if (!Thread.currentThread().isInterrupted())
          {    
            switch (msg.what)
            {    
              case 0:    
                pb.setMax(fileSize);
              case 1:    
                pb.setProgress(downLoadFileSize);    
                int result = downLoadFileSize * 100 / fileSize;    
                tv.setText(result + "%");    
                break;    
              case 2:    
                Toast.makeText(MainActivity.this, "文件预告完成", Toast.LENGTH_SHORT).show();   
                FileInputStream fis = null;
				try {
					fis = new FileInputStream(Environment.getExternalStorageDirectory() + File.separator + "/ceshi/" + filename);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
                Bitmap bitmap = BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图
                imageView.setImageBitmap(bitmap);
                break;    
              case -1:    
                String error = msg.getData().getString("error");
                Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();    
                break;    
            }    
          }    
          super.handleMessage(msg);    
        }    
      };
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pb=(ProgressBar)findViewById(R.id.progressBar);
        tv=(TextView)findViewById(R.id.textView);
        imageView = (ImageView) findViewById(R.id.imageView);
        tv.setText("0%");
        new Thread(){
            public void run(){
                try {
                	//预告文件,参数:第一个URL,第二个存放路径
                	down_file("http://cdnq.duitang.com/uploads/item/201406/15/20140615203435_ABQMa.jpeg", Environment.getExternalStorageDirectory() + File.separator + "/ceshi/");
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   
            }    
        }.start();    
    }    
	/**
	 * 文件预告
	 * @param url:文件的预告地址
	 * @param path:文件保存到本地的地址
	 * @throws IOException
	 */
    public void down_file(String url,String path) throws IOException{    
        //预告函数          
        filename=url.substring(url.lastIndexOf("/") + 1);
        //获取文件名    
        URL myURL = new URL(url);
        URLConnection conn = myURL.openConnection();    
        conn.connect();    
        InputStream is = conn.getInputStream();    
        this.fileSize = conn.getContentLength();//根据响应获取文件大小    
        if (this.fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");    
        if (is == null) throw new RuntimeException("stream is null"); 
        File file1 = new File(path);
        File file2 = new File(path+filename);
        if(!file1.exists()){
        	file1.mkdirs();
        }
        if(!file2.exists()){
        	file2.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(path+filename);    
        //把数据存入路径+文件名    
        byte buf[] = new byte[1024];
        downLoadFileSize = 0;    
        sendMsg(0);    
        do{    
            //循环读取    
            int numread = is.read(buf);    
            if (numread == -1)    
            {    
              break;    
            }    
            fos.write(buf, 0, numread);    
            downLoadFileSize += numread;    
            sendMsg(1);//更新进度条    
        } while (true);  
        sendMsg(2);//通知预告完成    
        try{    
            is.close();    
        } catch (Exception ex) {    
            Log.e("tag", "error: " + ex.getMessage(), ex);    
        }    
    }    
    //在线程中向Handler发送文件的预告量,进行UI界面的更新
    private void sendMsg(int flag)    
    {    
        Message msg = new Message();    
        msg.what = flag;    
        handler.sendMessage(msg);    
    }        
}

最后一定要注意的是:在AndroidManifest.xml文件中,添加访问网络的权限

<uses-permission android:name="android.permission.INTERNET"/>

到这里关于Android文件预告动态显示预告进度的小demo就为大家分享完毕,希望对大家的学习有所帮助。

tags:

上一篇  下一篇

相关:

HBase事务和并发控制机制原理

作为一款优秀的非内存数据库,HBase和传统数据库一样提供了事务的概念,只是HBase的事务是行级事务,可以保

使用Gradle插件进行代码分析

代码分析在大多数项目中通常是作为最后一个步骤(如果做了的话)完成的。其通常难以配置及与现有代码整合。

GridGain确认ApacheIgnite性能是Hazelcast的2倍

针对由 Hazelcast 的CEO,Greg Luck先生撰写的一篇有煽动性的博客,指责 Apache Ignite 社区”伪造”测试结

最详细的AndroidToolbar开发实践总结

过年前发了一篇介绍 Translucent System Bar 特性的文章 Translucent System Bar 的最佳实践 ,收到很多开发

Android中深入理解LayoutInflater.inflate()

由于我们很容易习惯公式化的预置代码,有时我们会忽略很优雅的细节。LayoutInflater以及它在Fragment的onCr

到日本这个小岛来,听听来自世界各地的心跳声

在濑户内海中,有座叫丰岛的小岛,这座岛以建筑师西泽立卫设计的丰岛美术馆而闻名。在美术馆的旁边,有一个

「不是很懂你们二次元」,可能是你还不懂那些ACG黑话

谢题主和 @lushark 同喵。题主既然是 b 站中人,那么想必很熟悉一个说法:DSSQ——不熟悉这个词的,大概也不

7年,她被囚禁、性虐,还生下了一个孩子

长达 7 年的非法拘禁和性虐待,还生下了一个从未见天日的孩子,这样骇人听闻的罪行,本身就很抢眼。然而这部

听起来有些残忍,不过人命确实不是无价的

这世界上真正“无价”的东西实在不多,人命并不是其中之一。人命是有价格的,而且明码标价,童叟无欺。当然

你们知道红豆汤圆在日本叫什么吗?

我喜欢在冬天吃一点能让全身都暖起来的甜品,这碗红豆汤圆,软糯甜香且温暖身心,不仅适合元宵节,也适合漫

站长推荐: