一、下载安装包
private class DownloadTask extends AsyncTask<String,Integer,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.e(TAG, "onPreExecute: " );
}
@Override
protected String doInBackground(String... strings) {
String fileUrl = strings[0];
int totalSize;
int downloadedSize = 0;
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "服务器连接失败";
}
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
FileOutputStream output = getActivity().openFileOutput("RE30.apk", MODE_PRIVATE);
byte data[] = new byte[1024];
totalSize = 0;
int count;
while ((count = input.read(data)) != -1) {
totalSize += count;
output.write(data, 0, count);
downloadedSize = (int) ((totalSize * 100) / fileLength);
publishProgress(downloadedSize);
}
output.flush();
output.close();
input.close();
return "下载完成";
} catch (Exception e) {
e.printStackTrace();
return "下载失败: " + e.getMessage();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
Log.e(TAG, "onProgressUpdate: "+values[0] );
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e(TAG, "onPostExecute: "+s );
File file=getActivity().getFilesDir();
Log.e(TAG, "doInBackground: 下载的文件的路径 "+ file.getAbsolutePath());
InstallApk(getActivity(),"/data/user/0/com.tyt.kitgf/files/RE30.apk");
btUpdate.setEnabled(true);
btFirmwareUpdate.setEnabled(true);
progressBar.setVisibility(View.GONE);
}
}
调用:
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(MyApp.Update_Address);//参数为下载地址
二、安装
1、安装程序的方法
private void InstallApk(Context context, String apkFilePath) {
File apkFile = new File(apkFilePath);
if (apkFile.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
安卓7以下系统 安装方法
2、在Manifest中配置provider
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.tyt.kitgf.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
authorities为 程序包名+fileprovider
3、在res/xml中创建 filepaths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<path>
<root-path name="files_apk"
path="/"/>
</path>
</paths>