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 windowFile fileLocation =newFile(context.getFilesDir(), fileName);Intent intent =newIntent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(fileLocation),"application/vnd.android.package-archive");
context.startActivity(intent);
参考:
http://stackoverflow.com/questions/8784404/download-and-install-an-application-apk-from-internal-memory-no-sd-card
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)