繁体   English   中英

Android - 我无法通过尝试打开文件,但可以从文件资源管理器中打开

[英]Android - I can't open a file from an attempt but from the file explorer

再会,

我正在制作一个应用程序,我必须从数据库中加载一些带有数据和图像或文档的卡片视图,当按下此元素以获取下载文件的选项时,完成下载后,提供从应用。 在打开文件(图像、word 文档、excel 等)之前,所有这些都运行良好,此时它不会通过 android studio 控制台或应用程序向我显示任何错误,只有在打开它显示为已损坏(当它是图像时,尽管如果我从文件资源管理器打开它,它会毫无问题地打开),而当它是一个文档时,它打开时就像文件是空的或好像它是一个新文件。

所以我通过下载管理器获取数据:

private void executeDownload() {
ProgressDialog progressDialog = new ProgressDialog(AssignedTasksDetailActivity.this);
progressDialog.setMessage("Descargando Archivo...");
progressDialog.setCancelable(false);
progressDialog.show();
// registrer receiver in order to verify when download is complete
registerReceiver(new DonwloadCompleteReceiver(), new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url_app));
request.setDescription("Descargando Archivo " + filename);
request.setTitle("Descargado "+ filename);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
progressDialog.dismiss();

}

然后我在下载完成时显示一个警报对话框,以提供打开文件的选项(这是我认为它失败的地方):

public class DonwloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)){
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(AssignedTasksDetailActivity.this);
        alertDialogBuilder.setTitle("Importante");
        alertDialogBuilder.setMessage("¿Desea abrir este archivo?");
        alertDialogBuilder.setCancelable(true);
        alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

            }
        });

        alertDialogBuilder.setPositiveButton("Abrir",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                cancel();
                Coop app = ((Coop)getApplicationContext());
                //File file = new File(filename);  // -> filename = maven.pdf
                File file = new File(Environment.DIRECTORY_DOWNLOADS, filename);
                Uri path = FileProvider.getUriForFile(AssignedTasksDetailActivity.this, "com.example.coop.fileprovider", file);
                String type = url_app.substring(url_app.lastIndexOf('.'), url_app.length());
                Intent intent = new Intent(Intent.ACTION_VIEW);


                if(type==".jpg" || type==".jpeg" || type==".png"){
                    intent.setDataAndType(path, "image/*");
                }else{
                    if(type==".pdf"){
                        intent.setDataAndType(path, "application/pdf");
                    }else{
                        intent.setData(path);
                    }
                }
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                try{
                    AssignedTasksDetailActivity.this.startActivity(intent);
                    cancel();
                }catch(ActivityNotFoundException e){
                    Toast.makeText(AssignedTasksDetailActivity.this, "No hay una aplicacion instalada para abrir este tipo de archivos", Toast.LENGTH_SHORT).show();
                    cancel();
                }
            }
        });
        alertDialogBuilder.show();
    }
}

}

我附上了我的 fileprovider 配置,看看这是否与它有关:

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.coop.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" />

和它的 xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
    <root-path name="root" path="." />

  </paths>

尝试使用 Toast 查看您尝试打开的文件的路径,这就是我抛出的问题:“内容://com.example.coop.fileprovider/root/Download/file_name.extension”。

我该如何解决?

提前致谢。

如果它在文件探索中工作,则检查文件路径是正确还是错误。 检查路径这个变量。 我遇到了同样的问题。 所以我找到了根本原因,这是错误的文件路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM