Ronak Khandelwal
Ronak Khandelwal

Reputation: 311

Android app view document files('.docx', '.pdf' ...)

I have an app which retrieves files for user it makes an api call and then returns a link to the file. My question is that should the app display the files inside the app itself or make use of any other app present in the phone to look at the file. If the app displays the files then what should I use? opening webview and using google docs is not an option since its very slow. Also I am using react-native so if any components are already present it would be great otherwise I have no issue writing a bridge.

Upvotes: 1

Views: 1600

Answers (1)

GPuschka
GPuschka

Reputation: 522

You should go with option 2. Don't try do do everything on your own. Ask the system if there is any app that can open the file, if no such app exists, notify the user that there is no app to open the file. You could also provide a link to an app that might open the file in question.

The important part when using this approach is that you need the mime types of the files since the system does the decision based on the provided type. Furthermore you may need a content provider so that other apps can actually open the files from your sandbox. Fortunately the framework does provide the File Provider just for this case. If you are not storing the files in the application directory you don't need the provider.

The code could look like this

File yourFile; //expecting the file to exist
String extension; //expecting the file extension (pdf, doc, ...) to exist
String mimetype; //may be null. You may obtain the mimetype from the server request in the http Content-Type header.
if (mimetype == null || mimetype.trim().isEmpty()) {
   //mimetype does no exist, try to guess mimetype from the extension
   mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
}
if (mimetype == null || mimetype.trim.isEmpty()) {
  //don't know what the mime type is. All we know is that it is a file we want to open.
  mimetype = "file/*";
}

Intent openFileIntent = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(yourFile)), mimetype);

if (openFileIntent.resolveActivity(getPackageManager()) != null) {
  this.startActivity(openFileIntent);
} else {
  Toast.makeText(this, R.string.no_application_can_open_file, Toast.LENGTH_SHORT).show();
}

Upvotes: 1

Related Questions