Search code examples
javaandroidandroid-file

Does Android have a similar class to Java's Desktop.getDesktop() for opening files or prompting the user to choose an application association?


What we are trying to do: We are attempting to replicate an existing Java Desktop application into an Android application (based upon Java as well). The desktop application uses the following Desktop class code to open any form of file type (e.g. docx, xlsx, txt, pdf. jpg, etc.) passed to it. This code will open the file to an associated application or prompt the user to select an application if none is associated or exists.

Our problem: Being new to Android development and system classes, we haven't been able to correctly identify if there is such a class in Android or the proper terminology to find it and could use your help.

Desktop.getDesktop().open(file); // Java version

Solution

  • I did resolve my issue based upon CommonWare's suggestion of using an Intent (see above). However, I did have a number of Uri path issues and needed to include the use of a FileProvider to handle the internal file path when building the Uri used in the Intent.

    I provided code which I used to build out my Uri path which was passed to the Intent (wrapped in the openFile(Uri uri) method. If it helps to see the full context of how I used the Intent, you can see it here: (Why would an Android Open File intent hang while opening an image?).

    The openFile() handling the actual Intent:

    private void openFile(Uri uri){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(uri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 2);
    }
    

    The TableRow onClick() creating the Uri from a TableRow value The Uri is built through the FileProvider beginning with File class calls.

    row.setOnClickListener(v -> {
    
        TableRow tablerow = (TableRow) v;
        TextView sample = (TextView) tablerow.getChildAt(1);
        String result = sample.getText().toString();
    
        File filePaths = new File(getFilesDir().toString());
        File newFile = new File(filePaths, result);
        Uri contentUri = getUriForFile(getApplicationContext(), "com.mydomain.fileprovider", newFile);
        openFile(contentUri);
    
    });