21
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WebViewClient#onPageStarted() が二回呼ばれることがある

Last updated at Posted at 2014-07-09

インターネット接続を切った状態でWebViewで適当なページヘアクセスすると、WebView#setWebViewClient() でセットしたクラスの onPageStarted() が二回呼ばれてしまいます。

stackoverflowによると、どうやらアクセスに失敗した時は以下の順でメソッドが呼ばれる模様。

onPageStarted()
onLoadResource()
onReceivedError()

onPageStarted()
onLoadResource()
onPageFinished() 

onPageStarted() の中で初期化処理をしているので、何度も呼ばせたくない!
のですが、こればかりは如何ともし難い。

onReceivedError() は一度しか呼ばれないので、このタイミングでフラグを立てて初期化処理をスキップすることで、どうにか解決する事が出来ました。
大体こんな感じ。どこか再試行のタイミングでフラグを折ってやる必要がある。

HogeActivity.java

// (前略)

private boolean mErrored;

@Override
public void onCreate(Bundle savedInstanceState) {
	// エラーのフラグ。これがtrueのときは初期化処理を行わない
	this.mErrored = false;
	
	// (中略)
	
	webView.setWebViewClient(new WebViewClient(){
		@Override
		public void onPageStarted (WebView view, String url, Bitmap favicon) {
			if (!mErrored) {
				// 初期化処理
			}
		}

		@Override
		public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
			mErrored = true;
		}
	});
}

// (後略)
21
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?