做了个小例子,是关于android文件下载过程中进度条的实现,有些地方还有不当的地方,其中文件下载部分是参考mars老师的代码的,有兴趣可以去关注一下mars老师,http://www.mars-droid.com
代码写的比较乱,建议去看看mars老师的视频。
多话不说直接上代码了:
main.xml页面布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/downloadTextButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="下载文本文件"/> <Button android:id="@+id/downloadMp3Button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="下载MP3文件"/> <EditText android:id="@+id/editText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请出输入文字!" android:lines="3"/> <Button android:id="@+id/textButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="测试"/> </LinearLayout>
DownloadActivity
public class DownloadActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
// public int fileSize=0;
// public int downloadFileSize=0;
private TextView textView;
private Button downloadTextButton;
private Button downloadMp3Button;
private Button textButton;
private EditText editText;
private ProgressDialog dialog = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadTextButton = (Button) this.findViewById(R.id.downloadTextButton);
downloadMp3Button = (Button) this.findViewById(R.id.downloadMp3Button);
//添加监听
downloadTextButton.setOnClickListener(new DownloadTextButtonListener());
downloadMp3Button.setOnClickListener(new DownloadMp3ButtonListener());
textView = (TextView) this.findViewById(R.id.textView);
editText = (EditText) this.findViewById(R.id.editText);
textButton = (Button) this.findViewById(R.id.textButton);
textButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
textView.setText(editText.getText().toString());
Toast.makeText(DownloadActivity.this, textView.getText().toString(), Toast.LENGTH_LONG);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch(id){
case DIALOG_DOWNLOAD_PROGRESS:
dialog = new ProgressDialog(this);
dialog.setMessage("downloading…");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(false);
dialog.show();
return dialog;
default:
return null;
}
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(!Thread.currentThread().isInterrupted()){
switch(msg.what){
case 0:
dialog.setMax(msg.arg1);
break;
case 1:
dialog.setProgress(msg.arg1);
break;
case 2:
dialog.dismiss();
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(DownloadActivity.this, error, 1).show();
break;
}
}
super.handleMessage(msg);
}
};
class DownloadTextButtonListener implements OnClickListener{
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// HttpDownloader httpDownloader = new HttpDownloader();
// String text = httpDownloader.download("http://zhangmenshiting.baidu.com/data/music/5789992/%E8%8D%B7%E5%A1%98%E6%9C%88%E8%89%B2.mp3?xcode=732ac4f76aeff611f08f3bb5c5f0aafe");
}
}
class DownloadMp3ButtonListener implements OnClickListener{
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
//打开进度条
showDialog(DIALOG_DOWNLOAD_PROGRESS);
Thread t = new Thread(runnable);
t.start();
}
}
Runnable runnable = new Runnable(){
@Override
public void run() {
HttpDownloader httpDownloader = new HttpDownloader();
int result = httpDownloader.download(DownloadActivity.this,"http://zhangmenshiting.baidu.com/data/music/5935874/%E6%BA%9C%E6%BA%9C%E7%9A%84%E6%83%85%E6%AD%8C.mp3?xcode=54e0a53865de98f9ba842c53eb1bf508", "music/", "e.mp3");
System.out.println(result);
String str =null;
if(result == 0){
str = "成功!";
}else if(result == 1){
str = "文件已存在!";
}else{
str = "失败!";
}
// Toast.makeText(DownloadActivity.this, "下载结果"+str, Toast.LENGTH_LONG).show();
}
};
public void sendMsg(int flag,int value){
Message message = new Message();
message.what = flag;
message.arg1 = value;
handler.sendMessage(message);
}
}
下面两个为下载的工具类:
FileUtils.java
public class FileUtils {
private String SDPATH;
/**
*
*/
public FileUtils() {
// TODO Auto-generated constructor stub
//获得当前外部存储设备的目录
SDPATH = Environment.getExternalStorageDirectory()+"/";
}
/**
* 在SD卡上创建文件
* @param fileName
* @return
*/
public File createSdFile(String fileName){
File file = new File(SDPATH + fileName);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
/**
* 创建SD卡目录
* @param dirName
* @return
*/
public File createSDDir(String dirName){
File file = new File(SDPATH + dirName);
file.mkdir();
return file;
}
public boolean isFileExist(String fileName){
File file = new File(SDPATH + fileName);
return file.exists();
}
public File writeToSDFromInput(Context context,String path,String fileName,InputStream input){
File file = null;
OutputStream output = null;
try {
createSDDir(path);
file = createSdFile(path + fileName);
output = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024];
int total = 0;
while((input.read(buffer)) != -1){
total = total + buffer.length;
output.write(buffer);
//更新下载进度条
((DownloadActivity)context).sendMsg(1,total);
}
output.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//下载完成
((DownloadActivity)context).sendMsg(2,0);
return file;
}
}
HttpDownloader.java
public class HttpDownloader {
private URL url = null;
/**
* 根据URL下载文件,前提是文件当中的内容为文本,返回值就是文件当中的内容
* @param urlStr
* @return
*/
public String download(String urlStr){
StringBuffer buffer = new StringBuffer();
String line = null;
BufferedReader reader = null;
try {
url = new URL(urlStr);
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
Log.e("io", "HttpURLConnection -> IOException");
e.printStackTrace();
}
} catch (MalformedURLException e) {
Log.e("url","url -> MalformedURLException");
e.printStackTrace();
}finally{
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return buffer.toString();
}
/**
* 该函数返回整形: -1代表下载出错,0代表下载成功,1代表下载文件已存在
* @param urlStr
* @param path
* @param fileName
* @return
*/
public int download(Context context,String urlStr,String path,String fileName){
InputStream input = null;
FileUtils fileUtils = new FileUtils();
if(fileUtils.isFileExist(path + fileName)){
((DownloadActivity)context).sendMsg(2,0);
return 1;
}else{
try {
input = getInputStreamFromUrl(context,urlStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File resultFile = fileUtils.writeToSDFromInput(context,path, fileName, input);
if(resultFile == null){
return -1;
}
}
return 0;
}
public InputStream getInputStreamFromUrl(Context context,String urlStr) throws IOException{
url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream s = conn.getInputStream();
((DownloadActivity)context).sendMsg(0,conn.getContentLength());
return s;
}
}
别忘记添加:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
下面是运行的结果图:
正在下载:
下载完成之后,我们在sdcard/music可以看到f.mp3文件
下面附上源码,可以自己修改,在例子中我是通过直接弹出的方式显示进度条的,这样在下载的时候我们就不能做其他的事情了,我们可以在布局文件中显示进度条,这样我们在下载的时候可以在文本框中输入一下内容,点击测试按钮之后文本框中的内容可以在上面的TextView中显示出来。
如果运行本例子,需要更改下载的url地址,我用的是百度的音乐下载,在测试中发现百度每次生成的连接只能下载一次。