gpt4 book ai didi

android - 如何使用android中的默认可用应用程序在android中打开下载的文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:20:07 26 4
gpt4 key购买 nike

我正在从服务器下载文件,下载完成后我必须打开一个文件。知道问题是文件可能是任何类型,所以我无法指定和 Intent 调用来打开具有静态名称的文件,就像我们打开 PDF 文件一样。我想要的是当一个文件被下载时,它会搜索是否有任何应用程序可用于打开该文件,否则它会弹出。我正在做所有这些内部 fragment 。这是我的下载代码:

public class DownloadFile extends AsyncTask<String, Void, Integer> {
String file_name = "";
File sdcard = Environment.getExternalStorageDirectory();
@Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpURLConnection url_conn = null;
byte[] bffr;

long totalSize = 0;
File directory = new File(
Environment.getExternalStorageDirectory()
+ "/xyz/download");
directory.mkdirs();
// 06-03 17:57:41.160: D/file name(6882):
file_name = "";
file_name = params[0];
Log.d("file name", file_name.toString());
url_conn = (HttpURLConnection) (new URL("http://example.com/uploads/" + file_name)).openConnection();
url_conn.setRequestMethod("GET");
url_conn.setDoOutput(true);
url_conn.connect();

if (url_conn.getContentLength() > 0) {
File imgFile = new File(sdcard + "/xyz/download/",file_name);
FileOutputStream fos = new FileOutputStream(imgFile);
InputStream is = url_conn.getInputStream();
totalSize = url_conn.getContentLength();
// Log.d("File Download Size ",totalSize+"");
long total = 0;
bffr = new byte[1024];
int bufferLength = 0;
while ((bufferLength = is.read(bffr)) > 0) {
total += bufferLength;
publishProgress("" + (int) ((total * 100) / totalSize));
fos.write(bffr, 0, bufferLength);
}
fos.close();
} else
Log.w(file_name.toString(), "FILE NOT FOUND");
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}

}

private void publishProgress(String... process) {
// TODO Auto-generated method stub
mprogressDialog.setProgress(Integer.parseInt(process[0]));
}

protected void onPostExecute(Integer unused) {
Log.d("after downloading file ", "file downloaded ");
switch (unused) {
case 0:
mprogressDialog.dismiss();
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(sdcard + "/xyz/download/",file_name)),
"MIME-TYPE");
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
app.getBaseContext().startActivity(install);
break;
}
}
}

在执行后,我尝试使用 Intent 打开它,但没有成功。任何想法表示赞赏

最佳答案

    File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);

if (type == null)
type = "*/*";

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);

intent.setDataAndType(data, type);

startActivity(intent);

关于android - 如何使用android中的默认可用应用程序在android中打开下载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31377367/

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