手机中文件的下载分为后台自动下载和前台下载,我总结了这两种下的实现代码,其中前台下载并实现下载进度条的实现。
第一种:后台下载
/**
* 后台在下面一个Apk 下载完成后返回下载好的文件
*
* @param httpUrl
* @return
*/
private File downFile(final String httpUrl) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
FileOutputStream fileOutputStream = null;
InputStream inputStream;
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
if (inputStream != null) {
file = getFile(httpUrl);
fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, length);
}
fileOutputStream.close();
fileOutputStream.flush();
}
inputStream.close();
}
//下载完成
//安装
installApk();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return file;
}
/**
* 根据传过来url创建文件
*
*/
private File getFile(String url) {
File files = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), getFilePath(url));
return files;
}
/**
* 截取出url后面的apk的文件名
*
* @param url
* @return
*/
private String getFilePath(String url) {
return url.substring(url.lastIndexOf("/"), url.length());
}
/**
* 安装APK
*/
private void installApk() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);
}
第二种
//下载apk程序代码
protected File downLoadFile(String httpUrl) {
// TODO Auto-generated method stub
final String fileName = "updata.apk";
File tmpFile = new File("/sdcard/update");
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
final File file = new File("/sdcard/update/" + fileName);
try {
URL url = new URL(httpUrl);
try {
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[256];
conn.connect();
double count = 0;
if (conn.getResponseCode() >= 400) {
Toast.makeText(Main.this, "连接超时", Toast.LENGTH_SHORT)
.show();
} else {
while (count <= 100) {
if (is != null) {
int numRead = is.read(buf);
if (numRead <= 0) {
break;
} else {
fos.write(buf, 0, numRead);
}
} else {
break;
}
}
}
conn.disconnect();
fos.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
//打开APK程序代码
private void openFile(File file) {
// TODO Auto-generated method stub
Log.e("OpenFile", file.getName());
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}
上面这种方式直接调用downFile方法,参数传个URL地址就可以了
第三种:
private String url="http://----------------------.apk";
private File file;
private ProgressBar pb;
private TextView tv;
private int fileSize;
private int downLoadFileSize;
private String filename;
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:
finish();
openFile(file);
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(DownLoadActivity.this, error, Toast.LENGTH_SHORT).show();
break;
}
}
super.handleMessage(msg);
}
};
new Thread() {
public void run() {
try {
down_file(url, "/sdcard/");
//下载文件,参数:第一个URL,第二个存放路径
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
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");
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);
file = new File(path + filename);
sendMsg(2);//通知下载完成
try {
is.close();
} catch (Exception ex) {
Log.e("tag", "error: " + ex.getMessage(), ex);
}
}
private void sendMsg(int flag) {
Message msg = new Message();
msg.what = flag;
handler.sendMessage(msg);
}
//打开APK程序代码
private void openFile(File file) {
// TODO Auto-generated method stub
Log.e("OpenFile", file.getName());
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}