How to open file with any exetension in Android?

前端 未结 3 756
走了就别回头了
走了就别回头了 2021-01-12 09:22

I have an app in which user can upload file with any exetention(.png,.mp3,.txt,.pdf

相关标签:
3条回答
  • 2021-01-12 09:47

    Pointing to the first part of your question:

    try
    {
      Intent intent = new Intent(Intent.ACTION_VIEW, uri);
      startActivity(intent);
    }
    catch (ActivityNotFoundException e)
    {
      //tel the user to install viewer to perform this action
    }
    

    There's no need to specify the type. It will get it from the data URI.

    0 讨论(0)
  • 2021-01-12 09:54

    The following code will work for every file type:

    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), fileMimeType);
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        // no Activity to handle this kind of files
    }
    

    Of course, there should be an Activity in the system that knows how to handle the file of a certain type. Hope this helps.

    0 讨论(0)
  • 2021-01-12 09:56
    public void openFile() {
        try {
            File file = new File(G.DIR_APP + fileName);
            fileExtension = fileName.substring(fileName.lastIndexOf("."));
            Uri path = Uri.fromFile(file);
            Intent fileIntent = new Intent(Intent.ACTION_VIEW);
            fileIntent.setDataAndType(path, "application/" + fileExtension);
            startActivity(fileIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(G.currentActivity, "Cant Find Your File", Toast.LENGTH_LONG).show();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题