权限
<uses-permission android:name="android.permission.REPLACE_EXISTING_PACKAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 获取网络状态 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.READ_LOGS" />
下载 保持apk路径要对应 android:resource="@xml/provider_paths" getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) 对应 /storage/emulated/0/Android/data/你的包名/files/目录
OutputStream output = null;
InputStream input = null;
try{
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
input = urlConn.getInputStream();
long size = urlConn.getContentLength();
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "xx.apk");
output = new FileOutputStream(file);
byte [] buffer = new byte[1024];
long total = 0;
int count = 0;
while((count = input.read(buffer)) != -1){
output.write(buffer,0,count);
output.flush();
total += count;
int pro = (int)(total*100/size);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
安装 getUriForFile 填上AndroidManifest.xml android:authorities
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "xxx.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = AppFileProvider.getUriForFile(BleActivity.this, "com.a.mybledemo.fileprovider", file);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
AndroidManifest.xml添加文件提供者FileProvider ,FileProvider是系统自带的
<provider
android:name="FileProvider"
android:authorities="com.sbas.mybledemo.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"
tools:replace="name,resource" />
</provider>
res/xml/provider_paths.xml external-files-path对应对应 /storage/emulated/0/Android/data/你的包名/files/目录
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path
name="download"
path="/Download"
/>
</paths>
|