Android中webview监控页面卡死

原文地址为: Android中webview监控页面卡死

由于webview在加载页面过程中或者加载完成后,页面可能会出现卡顿或崩溃的情况,此时程序后台是感知不到的,需要通过程序手段监测出来。

因此采取页面上定时发送心跳到webview后端,后端通过监测心跳来判断页面有没有死掉的情况。

一、先编写java相关文件HeartJavaScriptFunction.java,用于向js提供调用的接口函数:

public interface HeartJavaScriptFunction {

void onJsFunctionCalled(int tag);
}

二、编写CrashMonitor.java,用来判断页面心跳:

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class CrashMonitor {
private ScheduledExecutorService executorService = null;
private long oldpos = 0;
private int pauseNum = 0;
private OnCrashedListener onCrashedListener;
public interface OnCrashedListener {
void onCrashed();
}
public void setOnCrashedListener(OnCrashedListener listener) {
onCrashedListener = listener;
}
public boolean isWorking(){
boolean res = false;
if(executorService != null){
res = true;
}
return res;
}
public void updateTimer(long pos){
oldpos = pos;
}
public void monitorPageCrashed(final int period){
executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
if(oldpos > 0 && (new Date().getTime() - oldpos) > 1 * 60 * 1000){
pauseNum ++;
}
if(pauseNum >= 3){
oldpos = 0;
executorService.shutdown();
//do something
if(onCrashedListener != null){
onCrashedListener.onCrashed();
}
return;
}
}
},0,period, TimeUnit.MILLISECONDS);
}
}

三、webview调用监听程序:

		mWebView.addJavascriptInterface(new HeartJavaScriptFunction() {

@Override
public void onJsFunctionCalled(int tag) {
// TODO Auto-generated method stub
if(crashMonitor != null){
crashMonitor.updateTimer(new Date().getTime());
if(!crashMonitor.isWorking()){
crashMonitor.monitorPageCrashed(tag);
}
}
}
}, "Android");
crashMonitor.setOnCrashedListener(new CrashMonitor.OnCrashedListener() {

@Override
public void onCrashed() {
// TODO Auto-generated method stub
//页面卡死了
}
});

四、页面通过js定时发送心跳:

<script type="text/javascript">
var intv = 10 * 1000;
setInterval(function () {
if(typeof Android != "undefined"){
Android.onJsFunctionCalled(intv);
}
}, intv);
</script>



转载请注明本文地址: Android中webview监控页面卡死

猜你喜欢

转载自blog.csdn.net/dearbaba_1666/article/details/80910415
今日推荐