- 浏览: 181712 次
- 性别:
- 来自: 浙江
文章分类
最新评论
有些地方需要用到像下载时用到的进度条,我这里简单的做了个demo。
布局文件activity_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"
android:padding="10dp">
<Button
android:id="@+id/btnAddPro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加进程"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/llPro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
</ScrollView>
</LinearLayout>
接着就是往llPro中添加view,view的布局unit_process.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"
android:padding="10dp">
<TextView
android:id="@+id/tv_rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/tv_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ProgressBar
android:id="@+id/down_pb"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100" />
</LinearLayout>
代码实现:
package com.lml.process;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.client.ClientProtocolException;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnAdd;
LinearLayout llPro;
private int num=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llPro=(LinearLayout)findViewById(R.id.llPro);
btnAdd=(Button)findViewById(R.id.btnAddPro);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
final View view = inflater.inflate(R.layout.unit_process, null);
llPro.addView(view);
String source = "http://image.baidu.com/i?tn=download&ipn=dwnl&word=%E5%9B%BE%E7%89%87%E4%B8%8B%E8%BD%BD&ie=utf-8&fr=result&url=http%3A%2F%2Fimg2.pcpop.com%2FArticleImages%2F0x0%2F1%2F1061%2F001061672.jpg";
AsyTask at=new AsyTask(MainActivity.this,view,source);
at.execute();
}
});
}
private Handler handler = new Handler() {
ProgressBar pb;
TextView tv_rate,tv_name;
@Override
public void handleMessage(Message msg) {
// 定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted()) {
Object[] data= (Object[])(msg.obj);
View view =(View) data[0];
switch (msg.what) {
case 0:
pb=(ProgressBar)view.findViewById(R.id.down_pb);
tv_name=(TextView)view.findViewById(R.id.tv_name);
pb.setMax((Integer)data[1]);
tv_name.setText((String)data[2]);
break;
case 1:
pb=(ProgressBar)view.findViewById(R.id.down_pb);
tv_rate=(TextView)view.findViewById(R.id.tv_rate);
pb.setProgress((Integer)data[2]);
int result = (Integer)data[2] * 100 /(Integer) data[1];
tv_rate.setText(result + "%");
break;
case 2:
Toast.makeText(MainActivity.this, "文件下载完成", Toast.LENGTH_SHORT).show();
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
break;
}
}
super.handleMessage(msg);
}
};
public boolean downFile(String url, String path , View view) throws IOException {
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
URL absUrl = conn.getURL();// 获得真实Url
String filename = conn.getHeaderField("Content-Disposition");
if (filename == null || filename.length() < 1) {
filename = absUrl.getFile();
}
int fileSize = conn.getContentLength();// 根据响应获取文件大小
if (fileSize <= 0)
return false;
if (is == null)
return false;
File dir=new File(path+"/Mytext");
dir.mkdirs();
File file=new File(dir.getAbsolutePath(),"lml"+(num++)+".jpg");
if(file.exists()){
file.delete();
}
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
byte buf[] = new byte[1024];
int downLoadFileSize = 0;
Object[] data0=new Object[]{view,fileSize,filename };
sendMsg(0,data0);
do {
// 循环读取
int numread = is.read(buf);
if (numread == -1) {
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
Object[] data1=new Object[]{view,fileSize,downLoadFileSize };
sendMsg(1,data1);// 更新进度条
} while (true);
Object[] data1=new Object[]{view};
sendMsg(2,data1);// 通知下载完成
try {
is.close();
fos.close();
} catch (Exception ex) {
return false;
}
return true;
}
private void sendMsg(int flag,Object[] data) {
Message msg = Message.obtain(handler,flag, 0, 0,data);
handler.sendMessage(msg);
}
class AsyTask extends AsyncTask<String, Integer, Boolean> {
Context mContext;
View view;
String source;
public AsyTask(Context context,View view,String source) {
mContext = context;
this.view=view ;
this.source=source;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... arg0) {
Boolean isSuccess = false ;
try {
isSuccess = downFile(source,
Environment.getExternalStorageDirectory().getPath(),view);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isSuccess;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(!result){
llPro.removeView(view);
Toast.makeText(MainActivity.this, "下载失败!", Toast.LENGTH_LONG).show();
}
}
}
}
布局文件activity_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"
android:padding="10dp">
<Button
android:id="@+id/btnAddPro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加进程"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/llPro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
</ScrollView>
</LinearLayout>
接着就是往llPro中添加view,view的布局unit_process.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"
android:padding="10dp">
<TextView
android:id="@+id/tv_rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/tv_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ProgressBar
android:id="@+id/down_pb"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100" />
</LinearLayout>
代码实现:
package com.lml.process;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.client.ClientProtocolException;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnAdd;
LinearLayout llPro;
private int num=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llPro=(LinearLayout)findViewById(R.id.llPro);
btnAdd=(Button)findViewById(R.id.btnAddPro);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
final View view = inflater.inflate(R.layout.unit_process, null);
llPro.addView(view);
String source = "http://image.baidu.com/i?tn=download&ipn=dwnl&word=%E5%9B%BE%E7%89%87%E4%B8%8B%E8%BD%BD&ie=utf-8&fr=result&url=http%3A%2F%2Fimg2.pcpop.com%2FArticleImages%2F0x0%2F1%2F1061%2F001061672.jpg";
AsyTask at=new AsyTask(MainActivity.this,view,source);
at.execute();
}
});
}
private Handler handler = new Handler() {
ProgressBar pb;
TextView tv_rate,tv_name;
@Override
public void handleMessage(Message msg) {
// 定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted()) {
Object[] data= (Object[])(msg.obj);
View view =(View) data[0];
switch (msg.what) {
case 0:
pb=(ProgressBar)view.findViewById(R.id.down_pb);
tv_name=(TextView)view.findViewById(R.id.tv_name);
pb.setMax((Integer)data[1]);
tv_name.setText((String)data[2]);
break;
case 1:
pb=(ProgressBar)view.findViewById(R.id.down_pb);
tv_rate=(TextView)view.findViewById(R.id.tv_rate);
pb.setProgress((Integer)data[2]);
int result = (Integer)data[2] * 100 /(Integer) data[1];
tv_rate.setText(result + "%");
break;
case 2:
Toast.makeText(MainActivity.this, "文件下载完成", Toast.LENGTH_SHORT).show();
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
break;
}
}
super.handleMessage(msg);
}
};
public boolean downFile(String url, String path , View view) throws IOException {
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
URL absUrl = conn.getURL();// 获得真实Url
String filename = conn.getHeaderField("Content-Disposition");
if (filename == null || filename.length() < 1) {
filename = absUrl.getFile();
}
int fileSize = conn.getContentLength();// 根据响应获取文件大小
if (fileSize <= 0)
return false;
if (is == null)
return false;
File dir=new File(path+"/Mytext");
dir.mkdirs();
File file=new File(dir.getAbsolutePath(),"lml"+(num++)+".jpg");
if(file.exists()){
file.delete();
}
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
byte buf[] = new byte[1024];
int downLoadFileSize = 0;
Object[] data0=new Object[]{view,fileSize,filename };
sendMsg(0,data0);
do {
// 循环读取
int numread = is.read(buf);
if (numread == -1) {
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
Object[] data1=new Object[]{view,fileSize,downLoadFileSize };
sendMsg(1,data1);// 更新进度条
} while (true);
Object[] data1=new Object[]{view};
sendMsg(2,data1);// 通知下载完成
try {
is.close();
fos.close();
} catch (Exception ex) {
return false;
}
return true;
}
private void sendMsg(int flag,Object[] data) {
Message msg = Message.obtain(handler,flag, 0, 0,data);
handler.sendMessage(msg);
}
class AsyTask extends AsyncTask<String, Integer, Boolean> {
Context mContext;
View view;
String source;
public AsyTask(Context context,View view,String source) {
mContext = context;
this.view=view ;
this.source=source;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... arg0) {
Boolean isSuccess = false ;
try {
isSuccess = downFile(source,
Environment.getExternalStorageDirectory().getPath(),view);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isSuccess;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(!result){
llPro.removeView(view);
Toast.makeText(MainActivity.this, "下载失败!", Toast.LENGTH_LONG).show();
}
}
}
}
- Process.rar (1.3 MB)
- 下载次数: 0
发表评论
-
关于Android的webSocket的简单使用
2017-05-12 14:34 935使用第三方jar: autobahn-0.5.0.jar 连 ... -
Comparator自定义排序的使用
2017-05-11 14:18 720java对于集合的自定义排序方法有: Arrays.sort ... -
查看Android虚拟机文件相关命令
2017-05-02 14:12 529我们在虚拟机下添加文件后,想查看下文件是否正确创建,可在win ... -
android6.0创建文件问题
2017-05-02 12:58 550Android在6.0有了动态权限管理,在文件创建时就需要动态 ... -
xutils的http模块的简单使用
2017-04-28 16:05 488先导入xutils相关依赖: compile 'org.xut ... -
Litepal的简单使用
2017-04-27 17:21 602相关包下载地址:https://github.com/Lite ... -
Android下拉刷新上拉加载控件的使用
2017-04-21 10:46 805参考链接:http://www.jianshu.com/p/6 ... -
图片加载框架
2017-04-19 16:29 372图片加载框架: picasso ImageLoader -
Android的Service总结
2017-04-17 15:46 424参考链接:http://www.cnblogs.com/lwb ... -
解决ViewPager的addOnPageChangeListener不加载第一个的问题
2017-03-18 17:53 2590今天在使用ViewPager的时候发现个问题。 需求如下: ... -
clone方法的使用
2017-01-04 10:14 522由于Java有引用这一说,当两个变量指向同一块内存时,改变 ... -
Fragment无法切换问题
2016-12-16 14:57 2080Android有一个回收机制,当内存不足时,会自动回收相关内存 ... -
关于Material Design的CollapsingToolbarLayout初次使用
2016-12-16 13:38 579最近了解了下CollapsingToolbarLayout的使 ... -
MVP模式的学习
2016-12-10 15:15 622以前我写代码都是使用MVC模式,这种模式使Activity变得 ... -
Material Design:Android Design Support Library 介绍
2016-12-10 14:14 429参考链接 : https://blog.leancloud.c ... -
SpannableString简介
2016-12-10 14:03 388参考链接: http://www.cnblogs.com/ji ... -
getResources().getDrawable方法的废弃
2016-12-10 13:20 1164参考链接:http://www.jianshu.com/p/e ... -
关于AndroidStudio的Unsupported major.minor version 52.0异常
2016-12-10 13:15 2345参考链接:http://blog.csdn.net/fakin ... -
Android记录
2015-06-01 10:54 610http://tools.android-studio.org ... -
android自定义控件相关使用
2015-04-24 16:53 576用代码简单介绍下自定义控件的使用: 先看主activity: ...
相关推荐
Android 版本更新(含自定义更新框,自定义更新进度条)。
版本更新,自定义的dialog弹窗,以及自己定义的进度条,下载能直接使用
通过Handler进行传递值更新进度条,源代码,希望对你有所帮助
易语言在线更新更新进度条自动替换自身例程源码,替换新版,交互回调函数
NULL 博文链接:https://l540151663.iteye.com/blog/2022729
FTP上传(断点续传)更新进度条 公司项目第一个版本
WPF mvvm模式更新进度条
1. 很多程序需要根据处理业务的进度来更新进度条,进度条的目的是让用户能知道业务处理的进度,有进度条的程序更友好,让用户知道程序在运行,而不是没有响应。 博文: ...
类似于QQ音乐更新,绑定服务,AsyncTask HttpURLConnection下载xx.apk,同步用notification更新进度条。
Android中通过SeekBar手动控制ProgressBar与模拟下载自动更新进度条示例代码.zip
实现一个带进度条的下载: 1....下载的过程中对已经下载的长度进行累加,不断发送消息更新进度条 3.下载完成后发送的消息.rar,太多无法一一验证是否可用,程序如果跑不起来需要自调,部分代码功能进行参考学习。
更新进度条h的进度为p,进度标题为title。 例如,在命令行输入: >> h=mywaitbar; 生成的进度条如下图 11.JPG 更新进度为0.5,输入命令: >> mywaitbar; 生成的进度条...
鉴于 很多人在寻找 如何做一个带进度条的启动屏,所以特作此例子,供大家参考。因为启动屏和主程序是异步开始的,所以需要用到代理来更新进度条。
自定义通知栏布局,自定义进度条背景色,解决在部分手机上通知栏进度不更新的问题
进度条下载,实现实时更新实时下载的功能......
VC6.0写的复制文件夹以及子文件夹。将与exe同路径下的文件夹复制到用户指定的路径中,复制的时候进度条会实时更新(复制一个文件,进度条就走一步)。该例子中将Debug目录下的Machining Viewer文件夹复制到任意路径
JSP实现的进度条,主要实现的是在登陆的时候有一个打开的过程