问题是这样的:
我与某个 url 建立互联网连接并收到带有 app_example.apk 的 HttpResponse。
然后我想创建一个文件(.apk)
在带有此数据的 SD 卡中,以便此下载的应用程序
可以稍后安装。
如何将 HttpResponse 转换为 .apk 文件?
让我们澄清一些细节:
- 我必须通过互联网连接到我的服务器获取此 apk 文件
- 我不想安装 SD 卡上收到的此应用程序
- 所有这些都必须在我的代码中完成,我无法使用 android market
我目前正在写入该文件。
我正在做的是将 HttpResponse 转换为字节[],
然后使用 ObjectOutputStream 将 byte[ ] 写入文件(.apk)。
像这样:
// byte[] appByteArray - already has the internet response converted in bytes
try {
file = new File(Environment.getExternalStorageDirectory()+"/"+appName+".apk");
file.createNewFile();
FileOutputStream stream = null;
stream = new FileOutputStream(file, false);
ObjectOutputStream objectOut =
new ObjectOutputStream(new BufferedOutputStream(stream));
objectOut.writeObject(appByteArray);
objectOut.close();
} catch (Exception e) {
e.printStackTrace();
}
最后,文件就创建完成了
并有收到的内容。
当我尝试安装它时,
通过 VIEW 意图(使用默认安装程序)
我收到解析错误,指出找不到 AndroidManifest.xml。
我认为在这个过程中的某个步骤中,接收到的数据正在被损坏。
您还有其他方法来解决这个问题吗?
非常感谢
- 不要使用 ObjectOutputStream,字节数组被序列化为对象,而不是作为原始数据写入。
- 您确定您有SD卡写入权限吗? android.permission.WRITE_EXTERNAL_STORAGE
- 不要写入SD卡根目录。根目录中的文件数量可以受到限制。相反,请在 SD 卡上创建应用程序子目录。
这段代码对我有用:
try {
String filePath = Environment.getExternalStorageDirectory()
+ "/myappdir/" + appName + ".apk";
File file = new File(filePath);
file.getParentFile().mkdirs();
file.createNewFile();
BufferedOutputStream objectOut = new BufferedOutputStream(
new FileOutputStream(file));
objectOut.write(appByteArray);
objectOut.close();
} catch (Exception e) {
e.printStackTrace();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)