*添加权限
*
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
点击事件
case R.id.HttpDownload:
new Thread(new Runnable() {
@Override
public void run() {
initHttpDwonload();
}
}).start();
break;
代码实现
private void initHttpDwonload() {
String path = Environment.getExternalStorageDirectory() + File.separator + "123.apk";
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
URL url = new URL(apk);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// 获取文件总长度
int contentLength = urlConnection.getContentLength();
/* int responseCode = urlConnection.getResponseCode();*/
InputStream inputStream = urlConnection.getInputStream();
byte[] bytes = new byte[1024];
// 每次读取的长度
int Reanlength = 0;
long Currlength = 0;
// 不等于-1 证明取到了数据
while ((Reanlength = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, Reanlength);
Currlength += Reanlength;
final int progess = (int) (Currlength * 100 / contentLength);
progressBar.setProgress(progess);
Log.d(TAG, "initHttpDwonload: " + progess);
}
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}