如何通过Intent在Android中打开文件

tim*_*ner 16 filesystems android actionview android-intent

如何打开以前存储在"privat"文件系统中的文件?该文件由Web服务下载,应存储在本地fs中.尝试通过Intent(Action_View)打开文件时出现"奇怪"错误.虽然文件存在于文件系统中(在模拟器/ eclipse中看到文件浏览器中的文件),但它不会显示在启动的调用galery活动中.而不是图片,galery显示黑色屏幕没有内容(除了操作栏).尝试通过此方法打开pdf/movie/mp3文件时会出现同样的情况(pdf表示文件已损坏).

BTW:存储在本地fs上的数据有效(没有损坏),我从调试器下载文件(通过pull方法),文件可以在我的工作站上打开...

public void onAttachment(Context context, Attachment attachment) {
    try {
        //Attachment is a structured data object that contains of a byte[], filename and mimetype (like image/jpeg)
        FileOutputStream fos = FileOutputStream fos = context.openFileOutput(attachment.getAttachmentFileName(), Context.MODE_PRIVATE);
        fos.write(attachment.getBinary());
        fos.flush();
        fos.close();
        File f = context.getFileStreamPath(attachment.getAttachmentFileName());
        Uri uri = Uri.fromFile(f);          
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri,attachment.getAttachmentMimetype());
        context.startActivity(intent);                  
    } catch (IOException e) {
        e.printStackTrace();
    }
}           
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 12

您的代码中的附件是什么类型的?也许它会返回错误的mime类型?

这段代码适合我:

File file = new File("EXAMPLE.JPG");

// Just example, you should parse file name for extension
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(".JPG");

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), mime);
startActivityForResult(intent, 10);
Run Code Online (Sandbox Code Playgroud)


tim*_*ner 2

当将位置设置为“ openFileOutput("fileName", Activity.MODE_WORLD_READABLE)”时,它将起作用。Context.MODE_PRIVATE当设置为“ ”时,其他应用程序无法读取存储的数据(甚至用于查看)

请参阅stackoverflow 上的其他帖子