Sunday, 28 December 2014

Open a file with default application in Android

Here is a technique to program an Android application to open files using the default application that it is associated with them. A part of this technique can be found in many other sites on the internet. The advantage of this technique is that you don’t need to specify the type of the files or the application that is associated with them.
At first you create a method and you input in it a file object pointing to the  desired file (let’s call it testfile), then it is only necessary to create an intent setting setAction(android.content.Intent.ACTION_VIEW) and intentview.setData(Uri.fromFile(testfile)) and then start an activity with this intent. When this method is executed the application associated with the testfile is executed and it opens testfile without closing your application.
The only problem with this technique is that there might be the case where there is no application associated with testfile. This can happen when there is no suitable application or the testfile has no extension. In this case there is an exception “android.content.ActivityNotFoundException” that must be handled. A convenient technique is to enclose the code in a try-catch structure so as to catch the exception and execute some other code that will direct the program to do something else, like opening the file in a text viewer or display some message.
Here is the code

File testfile = new File(//path of testfile);

 public void openfile(File testfile){
        Intent intent1=new Intent();
        catch(android.content.ActivityNotFoundException exception){

            //Do something else