当前位置:操作系统 > 安卓/Android >>

android 内部存储 安装apk

 

 在做应用自动更新模块下载apk时遇到了内部存储和sd卡存储两种情况,存在sk卡中存储apk可以正常安装,可是在内部存储中安装apk时出现了parse error的问题。

在网上搜了搜,大致分为两种方案:

1、在存储时给文件设定权限

2、在使用文件之前更改文件权限

起初思路并没有理清,就开始尝试,多次尝试之后问题仍没有解决,再请教了大牛之后才开始一点点分析。

首先使用普通的文件读写

 

 File apkFile = new File(mSavePath, appName); 
FileOutputStream fos = new FileOutputStream(apkFile); 

 然后使用方案2:

 

 String chmodCmd = "chmod 666 " + apkfile.getAbsolutePath(); 
try { 
            Runtime.getRuntime().exec(chmodCmd); 
} catch (Exception e) { 
} 
Intent i = new Intent(Intent.ACTION_VIEW);         
String filePath = "file://" + apkfile.toString(); 
i.setDataAndType(Uri.fromFile(apkfile),"application/vnd.android.package-archive"); 
mContext.startActivity(i); 

 

问题解决了。

回过头来看方案一问什么不起作用,当我看文件时很吃惊,命名文件是下载下俩了,可是调用完了以后文件大小为0了,发现FileOutputStream fos = mContext.openFileOutput(appName,Context.MODE_WORLD_READABLE| Context.MODE_WORLD_WRITEABLE);在存文件和调用apk安装代码之前分别使用了一次,openFileOutput方法再次调用导致文件内容被清空,只需要在写文件的时候把文件权限置为读写权限便可。

 

 

String fileName = "tmp.apk";
FileOutputStream fos = openFileOutput(fileName,
        MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);

// write the .apk content here ... flush() and close()

// Now start the standard instalation window
File fileLocation = new File(context.getFilesDir(), fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(fileLocation),
                       "application/vnd.android.package-archive");
context.startActivity(intent);

 

 

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,