I'm trying to load multiple pages one after another, with a 30 seconds interval betweeen each load. This is my class:
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);
}
}
}
So, the logic is pretty simple: I've got a single WebView instance. Then, inside the for cycle I call postDelayed()
. It loads only google.com, the other two are not loaded, even if the Log says "PageLoaded". Is there a solution using the Handler
?
Ok, solved. Actually, the code that I've posted works. The problem comes when the pages that I wanted to load ask you to leave the page through a Javascript popup. You have two ways to handle this behaviour:
WebChromeClient
and handle the popupSo, this solution (the second one) works as well, even if more memory expensive (maybe?):
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);
}
}
}
Hope that this helps someone, thank you anyway!