Context.MODE_WORLD_READABLE,让安装程序可以有权限安装此文件。
下载代码如下:
path:网络url
apkname:你希望保存的文件名称
这样就可以实现再没有sd卡的条件下也可以顺利的升级自己的应用程序了。
下载代码如下:
path:网络url
apkname:你希望保存的文件名称
- public void downloadApktoappDir(String path,String apkname) throws IOException{
- URL url;
- FileOutputStream fos = null;
- BufferedInputStream bis = null;
- InputStream is = null;
- try {
- url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(5000);
- // 获取到文件的大小
- int size = conn.getContentLength();
- is = conn.getInputStream();
- fos = openFileOutput(apkname,
- Context.MODE_WORLD_READABLE);
- bis = new BufferedInputStream(is);
- byte[] buffer = new byte[1024];
- int len;
- int total = 0;
- while ((len = bis.read(buffer)) != -1) {
- fos.write(buffer, 0, len);
- // 获取当前下载量
- total += len;
- }
- } catch (MalformedURLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- fos.close();
- bis.close();
- is.close();
- }
- }
启动安装程序:
apkname:是保存文件时的文件名,
在需要进行升级的地方调用下面函数即可。
- public void installApkFromLocalPath(String apkname){
- Intent intent = new Intent();
- intent.setAction(Intent.ACTION_VIEW);
- //first method
- intent.setDataAndType(
- Uri.parse("file://"+getApplicationContext().getFilesDir().getAbsolutePath() + "/" + apkname),
- "application/and.android.package-archive");
- startActivity(intent);
- //second method
- // intent.setDataAndType(
- // Uri.fromFile(
- // new File(getApplicationContext().getFilesDir().getAbsolutePath() + "/" + apkname)),
- // "application/and.android.package-archive");
- // startActivity(intent);
- }
这样就可以实现再没有sd卡的条件下也可以顺利的升级自己的应用程序了。