Tuesday, August 2, 2011

View PDF file by starting activity with intent of ACTION_VIEW

By starting activity with intent of ACTION_VIEW, for "application/pdf", we can ask the installed PDF ready to open PDF file from our app.

View PDF file by starting activity with intent of ACTION_VIEW

package com.exercise.AndroidReadPDF;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class AndroidReadPDFActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

String path = "/sdcard/AndroidUsersGuide-2.3.4.pdf";
File targetFile = new File(path);
Uri targetUri = Uri.fromFile(targetFile);

Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");

startActivity(intent);
}
}

3 comments:

Jose Morales said...

Excellent!
But then, how can you close the third party app and return to your app programmatically?
Thanks

Andr.oid Eric said...

hello Jose Morales,

In my understanding, your app have NO right to close another app.

NishantNori said...

Hi,

I have some trouble with this code. This code just opens the PDF application but does not show it. It just opens the recent files tab in the application window. Am I to add any user permissions?