遇到一個需求:需要在頁面讀取完成後通知使用者(使用Alert或是Toast)
一開始只是很簡單的implement WebViewClinet中的:
@Override
public void onPageFinished(WebView view, String url)
onPageFinished()可以在Page 讀取完畢後獲得通知,但發現一個問題,若這個頁面進行多次(1次以上)的redirect,那麼,每redirect一次,就會notify一次onPageFinished(),這似乎無法達成我想要的動作。
假設我的頁面的流程如下:
- 開啟 http://DNS/app/test.jsp
- redirect to http://DNS/app/afterTest.jsp
直接以Logcat Log進行流程如下:
- onPageStarted() http://DNS/app/test.jsp
- shouldOverrideUrlLoading() http://DNS/app/afterTest.jsp
- onPageFinished() http://DNS/app/afterTest.jsp
- onPageStarted() http://DNS/app/afterTest.jsp
- onPageFinished() http://DNS/app/afterTest.jsp
因此原先只有直接implement onPageFinished()的作法會導致還沒進行到最後的afterTest.jsp就直接通知使用者;網路上找到建議作法如下,我自己也順利成功:
boolean loadingFinished = true; boolean redirect = false; mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) { if (!loadingFinished) { redirect = true; } loadingFinished = false; webView.loadUrl(urlNewString); return true; } @Override public void onPageStarted(WebView view, String url) { loadingFinished = false; //SHOW LOADING IF IT ISNT ALREADY VISIBLE } @Override public void onPageFinished(WebView view, String url) { if(!redirect){ loadingFinished = true; } if(loadingFinished && !redirect){ //HIDE LOADING IT HAS FINISHED } else{ redirect = false; } } });
利用redirect前會先notify shouldOverrideUrlLoading()來判定是否為redirect,若是,則在onPageFinished()時就不代表結束;而在每一次onPageFinished()時reset redirect flag;因此,上述範例的流程的flag變化如下:
loadingFinished=true, redirect=false
- onPageStarted() http://DNS/app/test.jsp
loadingFinished=false , redirect=false - shouldOverrideUrlLoading() http://DNS/app/afterTest.jsp
loadingFinished=false , redirect=true - onPageFinished() http://DNS/app/afterTest.jsp
loadingFinished=false , redirect=false - onPageStarted() http://DNS/app/afterTest.jsp
loadingFinished=false , redirect=false - onPageFinished() http://DNS/app/afterTest.jsp
loadingFinished=true , redirect=false
沒有留言:
張貼留言