我正在尝试一个接一个地加载多个页面,每次加载之间间隔30秒。这是我的班级:
public class MainActivity extends Activity {
private WebView wv;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wv = new WebView(this);
wv.setWebViewClient(new WebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
setContentView(wv);
String[] urlArr = {"http://www.google.com", "http://www.cnn.com", "http://www.wired.com"};
int delay = 30 * 1000;
Handler handler = new Handler();
for(int i = 0; i < urlArr.length; i++) {
MyRunnable runnable = new MyRunnable(urlArr[i]);
handler.postDelayed(runnable, delay);
delay = delay + 30 * 1000;
}
}
private class MyRunnable implements Runnable {
private String url;
public MyRunnable(String url) {
this.url = url;
}
public void run() {
wv.loadUrl(url);
Log.d("MainActivity", "PageLoaded: " + url);
}
}
}
所以,逻辑非常简单:我有一个WebView实例。然后,在for循环中,我调用postDelayed()
。它仅加载google.com,其他两个未加载,即使日志显示“PageLoaded”。是否有使用Handler
的解决方案?
答案 0 :(得分:0)
好的,解决了。实际上,我发布的代码有效。当我想加载的页面要求您通过Javascript弹出窗口离开页面时出现问题。您有两种方法来处理此行为:
WebChromeClient
并处理弹出窗口所以,这个解决方案(第二个)也能正常工作,即使内存更贵(可能?):
public class MainActivity extends Activity {
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] urlArr = {"http://www.google.com", "http://www.cnn.com", "http://www.wired.com"};
int delay = 30 * 1000;
Handler handler = new Handler();
for(int i = 0; i < urlArr.length; i++) {
WebView wv = new WebView(this);
wv.setWebViewClient(new WebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
MyRunnable runnable = new MyRunnable(urlArr[i], wv);
handler.postDelayed(runnable, delay);
delay = delay + 30 * 1000;
}
}
private class MyRunnable implements Runnable {
private String url;
private WebView wv;
public MyRunnable(String url, WebView wv) {
this.url = url;
this.wv = wv;
}
public void run() {
setContentView(wv);
wv.loadUrl(url);
Log.d("MainActivity", "PageLoaded: " + url);
}
}
}
希望这对某人有所帮助,不管怎样,谢谢你!