我正在寻找一段时间如何永远运行我的WebView。当调用android函数onPause()/ onResume()时。我的WebView再次启动。
我希望WebView继续下去。也许最好通过简单的HTML示例来解释:
<html><head><title>Webview test Android</title></head>
<body>
<h1><div id="counter"></div></h1>
<script>
var counter = 0;
document.getElementById("counter").innerHTML = counter;
setTimeout(function(){ count(); }, 1000);
function count() {
counter++;
document.getElementById("counter").innerHTML = counter;
console.log("counter: " + counter);
setTimeout(function(){ count(); }, 1000);
}
</script>
</body>
</html>
我在应用行为中想要的是:
> Open the app
+ Html page starts counting
> Press the home button / multitask button
+ Html page is still counting (or doing other stuff)
> Get back to the app
+ Html page is still counting and dont reload.
首先,我将自己的代码用于WebView。但是对于很多Android版本,我使用了chrome-webview example from github
我研究了android WebView方法,但我无法找到解决方案。我也试过mWebView.onPause(),mWebView.onResume()......没有结果。也许有人可以把我带到正确的方向。
这是主要功能:
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("main"," create ");
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.addJavascriptInterface(new NotificationBindObject(getApplicationContext()), "NotificationBind");
mWebView.getSettings().setDomStorageEnabled(true); // use localstorage
setUpWebViewDefaults(mWebView);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
if(mWebView.getUrl() == null) {
mWebView.loadUrl("file:///android_asset/www/index.html");
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the WebView state (including history stack)
mWebView.saveState(savedInstanceState);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
更新
几乎就是......我制作了一个运行WebView的服务。
public class TestService extends Service {
private static WebView w;
private static MainActivity ma;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
public static void setMain(MainActivity a) {
ma = a;
Log.e("main", " setData " );
setView();
}
private static void setView() {
w = (WebView) ma.findViewById(R.id.webView);
Log.e("main", " setData ");
w.getSettings().setDomStorageEnabled(true); // use localstorage
w.getSettings().setJavaScriptEnabled(true);
//ma.setUpWebViewDefaults(w);
w.loadUrl("file:///android_asset/www/index.html");
}
}
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("main"," create ");
if (savedInstanceState == null) {
setContentView(R.layout.activity_main);
Intent i = new Intent(MainActivity.this, TestService.class);
TestService.setMain(this);
MainActivity.this.startService(i);
} else {
...
}
...
}
现在我看到console.log(“counter”+ counter);在Eclipse中登录。唯一的问题是,当我回来时,布局中的WebView已经消失了......