gpt4 book ai didi

android - 如何从内部存储文件安装应用程序

转载 作者:行者123 更新时间:2023-11-29 17:46:02 26 4
gpt4 key购买 nike

我正在尝试下载一个 apk 文件然后安装它。
我已经使用外部存储目录完成了它,但是当我在本地目录中下载文件时,我无法解析它。

这是OnCreate方法的代码

final DownloadTask downloadTask = new DownloadTask(this);       
downloadTask.execute("http://file.appsapk.com/wp-content/uploads/apps-2/Gmail.apk","Gmail.apk");

DownloadTask 是从 AsyncTask 扩展而来的类。这是后台任务:

@Override
protected String doInBackground(String... sUrl) {
file_name=sUrl[1];
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if (isSDPresent) {
directory = new File(Environment.getExternalStorageDirectory()+File.separator+"app_directory");
}
else
{
directory = getFilesDir();

}
if (!directory.exists())
directory.mkdirs();
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}

int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(directory+"/"+file_name);
byte[] buffer = new byte[1024];
long total = 0;
int count;
while ((count = input.read(buffer)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(buffer, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (input != null)
input.close();

if (output != null)
output.close();
} catch (IOException ignored) {
}

if (connection != null)
connection.disconnect();
}
return null;
}

这是在第一个完成文件下载后运行的后执行方法:

   @Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
{
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
File file = new File(directory, file_name);
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
context.startActivity(promptInstall);
finish();

}

它可以完美地与外部存储一起运行,但不能与外部存储一起运行。为什么不呢?

最佳答案

尝试使用 openfileoutput() 而不是 OutputStream 将文件保存在内部存储中并使其可读。 http://developer.android.com/guide/topics/data/data-storage.html#filesInternal .打包错误主要是内部存储的权限问题。

关于android - 如何从内部存储文件安装应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26651357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com