【问题标题】:Android - I can't open a file from an attempt but from the file explorerAndroid - 我无法通过尝试打开文件,但无法从文件资源管理器中打开
【发布时间】:2019-12-08 15:10:38
【问题描述】:

早安,

我正在制作一个应用程序,我必须从数据库中加载一些带有数据和图像或文档的卡片视图,当按下此元素以获得下载文件的选项时,当完成下载时,提供打开的可能性它来自应用程序。在打开文件(图像、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”。

我该如何解决?

提前致谢。

【问题讨论】:

    标签: java android android-studio fileprovider


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 2020-07-30
      • 2023-01-12
      • 2015-12-15
      • 1970-01-01
      相关资源
      最近更新 更多