当前位置: 编程技术>移动开发
Android实现下载文件功能的方法
来源: 互联网 发布时间:2014-10-25
本文导语: 本文所述为Android实现下载文件功能的完整示例代码,对于学习和研究android编程相信会有一定的帮助,尤其是对Android初学者有一定的借鉴价值。 完整功能代码如下: package com.test; import java.io.File; import java.io.FileOutputStream; im...
本文所述为Android实现下载文件功能的完整示例代码,对于学习和研究android编程相信会有一定的帮助,尤其是对Android初学者有一定的借鉴价值。
完整功能代码如下:
package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main extends Activity {
private TextView mTextView01;
private EditText mEditText01;
private Button mButton01;
private static final String TAG = "DOWNLOADAPK";
private String currentFilePath = "";
private String currentTempFilePath = "";
private String strURL="";
private String fileEx="";
private String fileNa="";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView01 = (TextView)findViewById(R.id.myTextView1);
mButton01 = (Button)findViewById(R.id.myButton1);
mEditText01 =(EditText)findViewById(R.id.myEditText1);
mButton01.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
// 文件会下载至local端
mTextView01.setText("下载中...");
strURL = mEditText01.getText().toString();
/*取得欲安装程序之文件名称*/
fileEx = strURL.substring(strURL.lastIndexOf(".")
+1,strURL.length()).toLowerCase();
fileNa = strURL.substring(strURL.lastIndexOf("/")
+1,strURL.lastIndexOf("."));
getFile(strURL);
}
}
);
mEditText01.setOnClickListener(new EditText.OnClickListener()
{
public void onClick(View arg0){
mEditText01.setText("");
mTextView01.setText("远程安装程序(请输入URL)");
}
});
}
/* 处理下载URL文件自定义函数 */
private void getFile(final String strPath) {
try
{
if (strPath.equals(currentFilePath) )
{
getDataSource(strPath);
}
currentFilePath = strPath;
Runnable r = new Runnable()
{
public void run()
{
try
{
getDataSource(strPath);
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
}
};
new Thread(r).start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/*取得远程文件*/
private void getDataSource(String strPath) throws Exception
{
if (!URLUtil.isNetworkUrl(strPath))
{
mTextView01.setText("错误的URL");
}
else
{
/*取得URL*/
URL myURL = new URL(strPath);
/*创建连接*/
URLConnection conn = myURL.openConnection();
conn.connect();
/*InputStream 下载文件*/
InputStream is = conn.getInputStream();
if (is == null)
{
throw new RuntimeException("stream is null");
}
/*创建临时文件*/
File myTempFile = File.createTempFile(fileNa, "."+fileEx);
/*取得站存盘案路径*/
currentTempFilePath = myTempFile.getAbsolutePath();
/*将文件写入暂存盘*/
FileOutputStream fos = new FileOutputStream(myTempFile);
byte buf[] = new byte[128];
do
{
int numread = is.read(buf);
if (numread