webview中的android网页

时间:2012-09-05 12:32:00

标签: android webview offline

我想将网页存储在android项目文件夹中,以便用户也不需要互联网连接来查看网页。我正在使用android webview。我能够看到带有HTTP协议的网页。我的代码如下:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        WebView webview = (WebView) findViewById(R.id.webView1);
       // webview.loadUrl("http://www.mysite.com/index.html");

        webview.getSettings().setJavaScriptEnabled(true);
    }

但我想看到网页离线。有没有什么方法可以将网页存储为android项目文件夹中的资源,即使没有互联网连接也可以查看?

2 个答案:

答案 0 :(得分:1)

是的!

将它们放在/assets文件夹中,然后按以下方式访问它们:

webview.loadUrl("file:///android_asset/my_html_page.html"); 

这些问题已经得到解答:Webview load html from assets directory

答案 1 :(得分:0)

将网页存储在Asset文件夹中并使用

         public  File getfile(String filename) throws IOException {
    // TODO Auto-generated method stub
   String externalStorage_path          =Environment.getExternalStorageDirectory().toString();
   String state = Environment.getExternalStorageState();
   if (Environment.MEDIA_MOUNTED.equals(state)){
        File dir = new File(externalStorage_path + "/yourfilename");
        dir.mkdir();
        File mfile = new File(dir,filename);
        if( mfile.exists()==true)  return  mfile;
        else{
              try{
                  InputStream myInput =  mcontext.getAssets().open(filename);
                  String path =externalStorage_path+"/yourfilename";
                  OutputStream  myOutput = new FileOutputStream (path);
                  byte[] buffer = new byte[1024];
                  int length;
                  try {
                      while((length = myInput.read(buffer))>0)
                      myOutput.write(buffer,0,length);
                  }catch(FileNotFoundException e){Log.d("error",""+ e.toString());
                  }finally{
                      myOutput.flush();
                      myOutput.close();
                      myInput.close();
                  }
              }catch(IOException e){ }
              File dir1 = new File(externalStorage_path + "/yourfilename");
              dir1.mkdir();
              File mfile1 = new File(dir,filename);
              return mfile1;
        }
   }else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
       showToast("External storage has readonly access");
   } else if (Environment.MEDIA_REMOVED.equals(state)) {
       showToast("External storage not present");
   } else if (Environment.MEDIA_UNMOUNTABLE.equals(state)){
       showToast("External storage cannot be mounted. Sdcard problem");
   }

这会将文件写入您的存储空间,并可以由Adobe等其他应用程序共享打开。 jUST称这种方法。