gpt4 book ai didi

java - 无法从 Android 中的远程服务器下载 .apk 文件

转载 作者:太空宇宙 更新时间:2023-11-04 15:13:32 24 4
gpt4 key购买 nike

我想从我的网络服务器下载 .apk 文件,但我收到
java.io.FileNotFoundException: http://xxx/mygames/myapks/demo.apk 始终如此。

但是该文件存在于此 URL 中下面是我的代码,我在做什么。

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class InstallAPK 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 c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

File sdcard = Environment.getExternalStorageDirectory();
File myDir = new File(sdcard,"Android/data/com.sush19.app/temp");
myDir.mkdirs();
File outputFile = new File(myDir, "temp.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);

InputStream is = c.getInputStream();

byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.flush();
fos.close();
is.close();

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(sdcard,"Android/data/com.sush19.app/temp/temp.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
context.startActivity(intent);


} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}
}

在按钮上单击我正在调用,如下

InstallAPK downloadAndInstall = new InstallAPK();
downloadAndInstall.setContext(getApplicationContext());
downloadAndInstall.execute("http://xxx/mygames/myapks/demo.apk");

我也尝试使用文本文件,因为我刚刚将 demo.txt 文件上传到 http://xxx/mygames/myapks/demo.txt 我得到了相同的异常,但是当我浏览在浏览器中打开的 demo.txt 文件 URL。我需要做什么才能从 Web 服务器下载 .apk 文件。

我还包含了所有必需的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

我在以下位置收到上述异常:

InputStream is = c.getInputStream();

最佳答案

我认为你的android sdk版本是4.x,也许你可以尝试删除c.setDoOutput(true)这行代码。

关于java - 无法从 Android 中的远程服务器下载 .apk 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21087229/

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