【问题标题】:Unable to open local file in browser无法在浏览器中打开本地文件
【发布时间】:2013-08-28 04:40:13
【问题描述】:

(我已经检查过 SO 中的其他类似问题)

我正在尝试创建一个 HTML 编辑器。我有一个编辑文本,想在浏览器中打开其中输入的 HTML 代码。我通过将编辑文本内容复制到 .html 文件然后打开它来做到这一点。

String filename = "temp.html";
File file = new File(getActivity().getFilesDir(), filename);
FileOutputStream outputStream;
    try {
    outputStream = getActivity().openFileOutput(filename,
            Context.MODE_PRIVATE);
    outputStream.write(editText.getText().toString().getBytes());
    outputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
startActivity(intent);

我在清单中添加了<uses-permission android:name="android.permission.INTERNET" />。但是在我点击打开后,我得到的使用应用程序选项完成操作是 Adob​​e Reader 和 UTorrent 远程。没有显示浏览器。我的手机里有 Opera 和股票浏览器。我的代码有什么问题?我为

使用了自定义字体

注意:

  • 我不想在我的应用程序中使用 WebView。我只想在浏览器中打开它。
  • “getActivity()”,因为这段代码在片段中。

编辑:

File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/temp");
        dir.mkdirs();
        File file = new File(dir, "temp.html");
        FileOutputStream outputStream;
        try {
            outputStream = new FileOutputStream(file);
            outputStream.write(et.getText().toString().getBytes());
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
        startActivity(intent);

更改了将文件写入外部目录的代码。问题仍然存在。

【问题讨论】:

    标签: android html android-intent browser


    【解决方案1】:

    我的代码有什么问题?

    首先,第三方应用无法访问您的文件,因为它是内部存储上的私有文件。

    其次,浏览器应用不需要支持 file:// Uri 值,甚至是 content:// Uri 值(如果你想用它来向第三方应用公开私人文件)。

    如果要显示本地 HTML,请使用 WebView 小部件。或者,遍历可用的 Web 浏览器应用程序列表,直到找到支持 file://content:// Uri 方案的应用程序,然后鼓励用户安装该浏览器。

    【讨论】:

    • 所以我的解决方案是我必须创建可由第三方浏览器访问的文件?
    • @ArjunU:把它放在外部存储上。或者,use FileProvider 通过content:// Uri 从内部存储提供文件。而且,无论哪种情况,您仍然需要找到兼容的浏览器。请注意,在撰写本文时 Chrome 不兼容,尽管 Firefox 可能适用于外部存储上的文件。
    • 我将文件写入外部存储。同样的问题!
    • @ArjunU:您需要安装支持file:// 方案的浏览器。铬没有。 AOSP 浏览器应用程序没有。 Firefox 可能。
    • @ArjunU: 嗯...您可以尝试使用setDataAndType() 指定您的内容为text/html
    【解决方案2】:

    Android 的内置浏览器应用程序可以访问您内部存储的私有数据区域中的文件,但要完成它需要一些工作(我只花了整整两个星期才弄清楚这一点)。首先,让我们处理AndroidManifest.xml 文件。在文件顶部附近(就在<application> 块之前)您需要指定此“权限”:

      <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    

    &lt;application&gt; 块将包含各种 &lt;activity&gt; 块。一个将是您的主要 HTML 编辑器安装程序代码。另一个可能是实际的 HTML 编辑器。另一个必须是浏览器启动器。那个需要看起来像这样:

    <activity
      android:name="com.android.browser"
      android:parentActivityName="com.myHTMLeditor.Installer"
      android:allowTaskReparenting="true"
      android:autoRemoveFromRecents="true"
      android:launchMode="standard"
      android:documentLaunchMode="intoExisting"
      android:excludeFromRecents="true"
      android:exported="false"
      android:noHistory="true"
      android:screenOrientation="portrait"
      android:stateNotNeeded="true"
      >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.APP_BROWSER" />
        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.OPENABLE" />
        <data
          android.scheme="file"
          android.host="com.myHTMLeditor"
          android.path="/data/data/com.myHTMLeditor/files/MainPage.html"
        />
      </intent-filter>
    </activity>
    

    android.path 数据可能需要使用调试器进行验证。更多内容如下。

    现在对于Installer.java 文件--仅在此示例中命名,因为上面android.parentActivityName 中指定了“安装程序”。 .java 文件需要某些导入才能使活动与文件一起使用:

    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import java.lang.String;
    import java.io.File;
    import java.io.InputStream;
    import java.io.FileOutputStream;
    

    安装程序的活动类的第一部分需要这样的内容:

    public class Installer extends Activity
    { boolean btmp, passfail=false;   //declare various variables global to the class
      File apphome, fmd;
      InputStream inp;
      FileOutputStream fout;
      Intent Browse;
      Uri u;
      Uri.Builder b;
      String fn;
      int lng;
      byte[] buffer=new byte[1024];
    

    实际执行安装的类函数或方法需要这样的代码:

    public void doInstall()
    { apphome=getFilesDir(); //VERIFY WITH DEBUGGER (for Manifest file): /data/data/com.myHTMLeditor/files
      apphome.setReadable(true, false);  //THIS IS KEY to letting the browser access files
      apphome.setWritable(true, false);  // in your application's private directory
    

    如果安装过程在那个目录中创建了一个文件,你需要这样的东西:

      fn=apphome.getPath()+"/MainPage.html"; //create file name
      fmd=new File(fn);                      //create file object
      btmp=fmd.createNewFile();              //create actual file
      if(btmp)
      { fout=new FileOutputStream(fmd);
        while( /*you have data to put into the file, fetch some of it into the byte-buffer */ )
          fout.write(buffer, 0, lng);  //lng is number of bytes put into the buffer
        fout.close();
      }
      if(btmp) //if successfully created the file, need to make it readable by the browser, too!
      { fmd.setReadable(true, false);
        fmd.setWritable(true, true);
      }
    
      passfail=true; //only do this when satisfied that all files are installed properly!
    

    现在启动浏览器以加载MainPage.html 文件的函数/方法:

    public void runBrowser(View vw)
    { if(passfail)
      { Browse = new Intent(Intent.ACTION_VIEW, Uri.parse("file://"+apphome.getPath()+"/MainPage.html"));
        Browse=Browse.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"));
        Browse=Browse.addCategory(Intent.CATEGORY_LAUNCHER);
        Browse=Browse.addCategory(Intent.CATEGORY_APP_BROWSER);
        Browse=Browse.addCategory(Intent.CATEGORY_DEFAULT);
        Browse=Browse.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Browse=Browse.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Browse=Browse.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        b=new Uri.Builder();
        b=b.encodedAuthority(apphome.getPath());
        b=b.scheme("file");
        b=b.path("/MainPage.html");
        u=b.build();
        u.getHost(); //this works to set the internal "host" property from the "authority" property
        Browse=Browse.setDataAndNormalize(u);
        startActivity(Browse);
    } }
    

    最后一点:我在这项工作中使用的是 Android API 21。我没有看到早期的 API 版本可以做到这一点。

    【讨论】:

      猜你喜欢
      • 2014-04-27
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      相关资源
      最近更新 更多