Context.MODE_WORLD_READABLE,让安装程序可以有权限安装此文件。
下载代码如下:
path:网络url
apkname:你希望保存的文件名称
这样就可以实现再没有sd卡的条件下也可以顺利的升级自己的应用程序了。
下载代码如下:
path:网络url
apkname:你希望保存的文件名称
- publicvoiddownloadApktoappDir(Stringpath,Stringapkname)throwsIOException{
- URLurl;
- FileOutputStreamfos=null;
- BufferedInputStreambis=null;
- InputStreamis=null;
- try{
- url=newURL(path);
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- conn.setConnectTimeout(5000);
- //获取到文件的大小
- intsize=conn.getContentLength();
- is=conn.getInputStream();
- fos=openFileOutput(apkname,
- Context.MODE_WORLD_READABLE);
- bis=newBufferedInputStream(is);
- byte[]buffer=newbyte[1024];
- intlen;
- inttotal=0;
- while((len=bis.read(buffer))!=-1){
- fos.write(buffer,0,len);
- //获取当前下载量
- total+=len;
- }
- }catch(MalformedURLExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }catch(IOExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }finally{
- fos.close();
- bis.close();
- is.close();
- }
- }
启动安装程序:
apkname:是保存文件时的文件名,
在需要进行升级的地方调用下面函数即可。
- publicvoidinstallApkFromLocalPath(Stringapkname){
- Intentintent=newIntent();
- intent.setAction(Intent.ACTION_VIEW);
- //firstmethod
- intent.setDataAndType(
- Uri.parse("file://"+getApplicationContext().getFilesDir().getAbsolutePath()+"/"+apkname),
- "application/and.android.package-archive");
- startActivity(intent);
- //secondmethod
- //intent.setDataAndType(
- //Uri.fromFile(
- //newFile(getApplicationContext().getFilesDir().getAbsolutePath()+"/"+apkname)),
- //"application/and.android.package-archive");
- //startActivity(intent);
- }
这样就可以实现再没有sd卡的条件下也可以顺利的升级自己的应用程序了。