2012-09-05 82 views
0

我想在android項目文件夾中存儲網頁,以便用戶不需要互聯網連接來查看網頁。我正在使用android webview。我能夠使用HTTP協議查看網頁。我的代碼如下:在webview中的android網頁

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項目文件夾中的資源,並查看即使沒有互聯網連接?

+0

可能會重複[this](http://stackoverflow.com/questions/4563291/save-webpages-for-offline-browsing) – Shrikant

回答

1

是!

,把它們放進/assets文件夾,並訪問他們像這樣:

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

這個問題已經有了答案:Webview load html from assets directory

0

店在您的資產文件夾中的網頁,並使用

  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)共享以打開。只是稱這種方法。

+1

呃,這似乎是矯枉過正只是顯示一個頁面。 –

相關問題