How to open Excel, .doc files in Webview in Android?

后端 未结 2 934
鱼传尺愫
鱼传尺愫 2021-02-14 20:23

How can I open Excel and .doc file in Android webview. Can google doc support it?

2条回答
  •  忘掉有多难
    2021-02-14 20:54

    If you want to open document file from Internal Storage like file:///data/user/0/com.sample.example/files/documents/sample.docx then you can not use

    urlWebView.loadUrl("http://docs.google.com/gview?embedded=true&url="+"YOUR_DOC_URL_HERE");
    

    You have to open docx file from external app like google docs, MS Word etc., For that you can use FileProvider


    Add in AndroidManifest.xml file.

    
     
       
     
    
    

    Add res/xml/file_paths.xml file

    
    
      
    
    

    Finally Add code for opening docx file in MainActivity.java file

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
    builder.detectFileUriExposure();
    
    Uri docUri = FileProvider.getUriForFile(getApplicationContext(), 
      "com.sample.example.provider", 
      new File("/data/user/0/com.sample.example/files/documents/sample.docx")); // same as defined in Manifest file in android:authorities="com.sample.example.provider"
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(docUri, "application/msword");
    try{
       intent.setFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
       Intent chooser = Intent.createChooser(intent,"Open With..");
       startActivity(chooser);
    } catch (ActivityNotFoundException e) {
       //user does not have a pdf viewer installed
       Log.d(LOG_TAG, "shouldOverrideUrlLoading: " + e.getLocalizedMessage());
       Toast.makeText(MainActivity.this, "No application to open file", Toast.LENGTH_SHORT).show();
    }
    

提交回复
热议问题