【发布时间】:2018-10-09 14:04:57
【问题描述】:
我正在尝试创建一种机制,让应用通过从应用内下载和安装更高版本的 APK 来更新自身。
我有一个位于服务器上的 APK,如果我只需导航到 URI 然后打开 .apk 文件,它就可以正常安装。当我尝试以编程方式安装它时,问题就来了。我收到“解析错误 - 解析包时出现问题”
目标手机允许从未知来源和AndroidManifest.xml 内安装我请求这些权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.REQUEST_WRITE_PERMISSION"/>
执行更新的代码取自 StackOverflow 上的另一个线程,并稍作更改以适合我的特定情况。
public class UpdateApp extends AsyncTask<String,Void,Void> {
private Context context;
public void setContext(Context contextf){
context = contextf;
}
@Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.connect();
File file = context.getCacheDir();
file.mkdirs();
File outputFile = new File(file, "update.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(outputFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (Throwable ex) {
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
我可以尝试什么来了解为什么 APK 在从代码中安装时会生成错误,但在从服务器下载时安装时没有问题?
该应用正在为 API 23 构建,但一旦完成,它将需要与 API 24 一起使用。
【问题讨论】:
-
“UpdateApp”异步任务运行了多少次?由于文件名每次都相同,因此可能会发生文件被多次下载且无效的情况。尝试附加
system.getcurrenttimemillis() -
感谢您的建议,但这不是问题所在。每次调用应用程序时,“UpdateApp”只会运行一次,但当然,可能会遗留以前的文件。我已将代码更改为
File outputFile = new File(file, "update" + System.currentTimeMillis() + ".apk");,但这并没有改变行为。
标签: android apk auto-update