How to open a file in Android via an Intent

前提是你 提交于 2019-12-23 06:56:09

问题


how can I open a file that has been previously stored in the "privat" filesystem? The file is being downloaded by a webservice and should be stored on local fs. I got a "strange" error when trying to open the file via an Intent (Action_View). Although the file is present in the filesystem (saw the file in the file explorer in emulator/eclipse) it won't be shown in the calling galery activity that is launched. Instead of the picture the galery shows a black screen with not content in there (except the action bar). The same occurs when trying to open a pdf/movie/mp3 file via this method (pdf says for example that the file is corrupt).

BTW: The data that has been stored on the local fs is valid (not corrupt), I downloaded the files from debugger (via pull method) and the files can be opened on my workstation...

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();
    }
}           

回答1:


What is the type of the Attachment in your code? Perhaps it returns wrong mime type?

This code works for me:

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);



回答2:


You cannot open files that are not on the sdcard like that. You'll need to copy the file to the sdcard and then opening it.




回答3:


When setting the location to "openFileOutput("fileName", Activity.MODE_WORLD_READABLE)" it will work. Other apps cannot read the data (even for viewing) stored when setting to "Context.MODE_PRIVATE"

see other post on stackoverflow



来源:https://stackoverflow.com/questions/12585747/how-to-open-a-file-in-android-via-an-intent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!