1、先建一个DownloadAPKFileTask类,继承AsyncTask
public class DownloadAPKFileTask extends AsyncTask<String, Void, File> {
// 文件路径
private String filePath;
private String fileName;
private Activity mContext;
private DownloadAPKListener listener;
private String savePath;
public DownloadAPKFileTask(Activity context, String downloadUrl, String fileName, DownloadAPKListener listener) {
mContext = context;
this.filePath = downloadUrl;//"http://192.168.0.125:8081/static/publish/app-debug.apk";
this.listener = listener;
this.fileName = fileName;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (null != listener) {
listener.showProgressBar();
}
}
//HGYDNew--自己的项目名
@Override
protected File doInBackground(String... params) {
savePath = Environment
.getExternalStorageDirectory().getAbsolutePath()
+ File.separator
+ "HGYDNew"
+ File.separator
+ fileName;
File downloadFile = new File(savePath);
if (downloadFile.exists()) {
downloadFile.delete();
}
if (!downloadFile.getParentFile().exists()) {
downloadFile.getParentFile().mkdirs();
}
try {
URL url = new URL(filePath);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
// 获取文件输出流对象
OutputStream outputStream = new FileOutputStream(downloadFile);
int bytesRead = 0;
// 创建缓冲区字节数组
byte[] buffer = new byte[2048];
int lastProgress = 0;
int currentProgress = 0;
while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
if (isCancelled()) {
break;
}
outputStream.write(buffer, 0, bytesRead);
currentProgress = (int) (downloadFile.length() * 100 / conn.getContentLength());
if (currentProgress != lastProgress) {
lastProgress = currentProgress;
listener.onProgress(lastProgress);
}
}
outputStream.close();
inputStream.close();
return downloadFile;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(File result) {
super.onPostExecute(result);
if (isCancelled()) {
listener.onResult(null);
}
if (result != null && result.exists() && null != listener) {
listener.onResult(result);
} else {
// ToastUtil.showToast(mContext.getResources().getString(R.string.download_file_fail));
//提示下载失败
listener.onResult(null);
}
}
public interface DownloadAPKListener {
void onResult(File file);
void onProgress(int progress);
void showProgressBar();
}
}
2、在res下新建xml文件夹,然后新建filepaths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<external-path
name="external_path"
path="." />
</paths>
</resources>
3、在drawable下新建bg_progress_download.xml文件,下载进度条的方法
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/progress">
<clip>
<shape>
<corners android:radius="10dp" />
<gradient
android:angle="0"
android:endColor="@color/color_ccb799"
android:startColor="@color/color_ccb799" />
</shape>
</clip>
</item>
</layer-list>
4、在layout下,main.xml中添加进度条创建方法
<ProgressBar
android:id="@+id/pb_update"
android:visibility="gone"
android:layout_width="277.5dp"
android:layout_height="7.5dp"
android:layout_centerInParent="true"
android:indeterminate="false"
android:indeterminateOnly="false"
android:max="100"
android:progressDrawable="@drawable/bg_progress_download" />
5、color文件下添加进度条颜色值
<!--下载条颜色-->
<color name="color_ccb799">#ccb799</color>
6、配置AndroidManifest.xml
一、读取文件权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES_REQUESTCODE" />
二、application配置方法
<!--配置方法,com.example.hgydnew是你自己项目的包名-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.hgydnew.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
7、MainActivity中调用方法
一、全局定义
//更新
private DownloadAPKFileTask task;
private ProgressBar pb_update;
private static final int UPDATE = 1000;
private static final int HIDE = 1001;
private static final int SHOW = 1002;
二、onCreate
//更新代码
pb_update = view.findViewById(R.id.pb_update);
task = new DownloadAPKFileTask(getActivity(), "https://download.baonahao.com/client/android/baonahao/jiayischool.apk", "zhxsfApp.apk", new DownloadAPKFileTask.DownloadAPKListener() {
@Override
public void onResult(File file) {
Message obtain = Message.obtain();
obtain.what = HIDE;
obtain.arg1 = 0;
handler.sendMessage(obtain);
if (null != file) {
getInstallIntent(file);
}
}
@Override
public void onProgress(int progress) {
// LogUtil.e("progress : " + progress);
Message obtain = Message.obtain();
obtain.what = UPDATE;
obtain.arg1 = progress;
handler.sendMessage(obtain);
}
@Override
public void showProgressBar() {
Message obtain = Message.obtain();
obtain.what = SHOW;
obtain.arg1 = 0;
handler.sendMessage(obtain);
}
});
三、Handler调用
//Handler方法
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE:
pb_update.setProgress(msg.arg1);
break;
case SHOW:
pb_update.setVisibility(View.VISIBLE);
break;
case HIDE:
pb_update.setVisibility(View.GONE);
try {
if (null != task) {
task.cancel(true);
task = null;
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
};
四、定义getInstallIntent方法
private void getInstallIntent(File file) {
Uri uri = null;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory("android.intent.category.DEFAULT");
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0 Android NF
//com.xxx.xxx.fileprovider为上述manifest中provider所配置相同
//com.example.hgydnew是你自己项目的包名
uri = FileProvider.getUriForFile(getContext(), "com.example.hgydnew.fileprovider", file);
intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//7.0以后,系统要求授予临时uri读取权限,安装完毕以后,系统会自动收回权限,该过程没有用户交互
} else {//7.0以下
uri = Uri.fromFile(file);
intent.setAction(Intent.ACTION_VIEW);
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
getContext().startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
五、重写方法
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 1:
task.execute();
break;
default:
break;
}
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
六、点击调用-先获取权限,然后调用 task.execute()
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED&&ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},1);
} else {
task.execute();
}
网友评论