业务场景:MainActivity中有4个tab,分别为 webview加载斗鱼主页,视频播放,webview加载五星体育,地图等四个模块。在加载web的时候发现内存泄露。

首先不能直接在xml写webview组件,用FrameLayout做容器,java中动态添加:

...

mWebView = new WebView(MyApplication.getContext());

mLlayout_webview.addView(mWebView);

弱引用

经测试,通过给webview所在的activity设置为独立进程,然后在改activity的ondestory()方法干掉进程就可以了。Acitvity中的代码

@Override

protected void onDestroy() {

unbinder.unbind();

if (EventBus.getDefault().isRegistered(this)) {

EventBus.getDefault().unregister(this);

}

tellServiceUnbind();

unbindService(serviceConnection);

releaseResource();

/**

* 解决Activity中

* https://www.cnblogs.com/ganchuanpu/p/9182968.html

* 为加载WebView的界面开启新进程,在该页面退出之后关闭这个进程。

*/

android.os.Process.killProcess(android.os.Process.myPid());

super.onDestroy();

}

完整的webview 代码

public class WuXingFragment extends BaseFragment {

private WebSettings webSettings;

public static WuXingFragment getInstance() {

WuXingFragment fragment = new WuXingFragment();

return fragment;

}

private static final String url = "http://sports.sina.com.cn/gsports.shtml#263363145";

private View mView;

private WebView mWebView;

private RelativeLayout loading_over;

private boolean isSuccess = false;

private boolean isError = false;

private LinearLayout ll_control_error,mLlayout_webview;

@Nullable

@Override

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

mView = inflater.inflate(R.layout.layout_webview, container, false);

mWebView = new WebView(MyApplication.getContext());

mLlayout_webview = mView.findViewById(R.id.llayout_webview);

mLlayout_webview.addView(mWebView);

return mView;

}

@Override

public void onResume() {

super.onResume();

// webview 优化 据说可以省电

webSettings.setJavaScriptEnabled(true);

}

@Override

public void onStop() {

super.onStop();

// webview 优化 据说可以省电

webSettings.setJavaScriptEnabled(false);

}

private void doAction() {

webSettings = mWebView.getSettings();

mWebView.setInitialScale(25);

webSettings.setJavaScriptEnabled(true);

webSettings.setJavaScriptEnabled(true);

webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

webSettings.setUseWideViewPort(true);//关键点

webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

webSettings.setDisplayZoomControls(false);

webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本

webSettings.setAllowFileAccess(true); // 允许访问文件

// webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮

// webSettings.setSupportZoom(true); // 支持缩放

webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

webSettings.setDomStorageEnabled(true);

webSettings.setPluginState(WebSettings.PluginState.ON);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

}

mWebView.loadUrl(url);

//设置视图客户端

mWebView.setWebViewClient(new MyWebViewClient(getActivity()));

// mWebView.setWebViewClient();

}

class MyWebViewClient extends WebViewClient {

protected WeakReference activityRef;

public MyWebViewClient(Activity activity) {

this.activityRef = new WeakReference<>(activity);

}

@Override

public boolean shouldOverrideUrlLoading(WebView view, String url) { //重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边

if (this == null) {

return false;

}

Activity activity = activityRef.get();

if (activity != null) {

//调用拨号程序

if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:") || url.startsWith("smsto:")) {

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

activity.startActivity(intent);

return true;

}

}

return false;

}

@Override

public void onPageFinished(WebView view, String url) {

}

@Override

public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

//6.0以下执行

updateUI();

}

@Override

public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {

super.onReceivedError(view, request, error);

//6.0以上执行

updateUI();

}

}

private void updateUI() {

isError = true;

isSuccess = false;

mWebView.setVisibility(View.GONE);

ll_control_error.setVisibility(View.VISIBLE);

}

@Override

public void onDestroyView() {

release();

super.onDestroyView();

}

@Override

public void onDestroy() {

release();

super.onDestroy();

}

private void release() {

if (null != mWebView) {

// 如果先调用destroy()方法,则会命中if (isDestroyed()) return;这一行代码,需要先onDetachedFromWindow(),再

// destory()

ViewParent parent = mWebView.getParent();

if (parent != null) {

((ViewGroup) parent).removeView(mWebView);

}

mWebView.stopLoading();

// 退出时调用此方法,移除绑定的服务,否则某些特定系统会报错

mWebView.getSettings().setJavaScriptEnabled(false);

mWebView.clearHistory();

mWebView.clearView();

mWebView.removeAllViews();

mWebView.destroy();

}

releaseAllWebViewCallback();

}

// 这个方法我这里暂时没起作用

public void releaseAllWebViewCallback() {

if (android.os.Build.VERSION.SDK_INT < 16) {

try {

Field field = WebView.class.getDeclaredField("mWebViewCore");

field = field.getType().getDeclaredField("mBrowserFrame");

field = field.getType().getDeclaredField("sConfigCallback");

field.setAccessible(true);

field.set(null, null);

} catch (NoSuchFieldException e) {

if (BuildConfig.DEBUG) {

e.printStackTrace();

}

} catch (IllegalAccessException e) {

if (BuildConfig.DEBUG) {

e.printStackTrace();

}

}

} else {

try {

Field sConfigCallback = Class.forName("android.webkit.BrowserFrame").getDeclaredField("sConfigCallback");

if (sConfigCallback != null) {

sConfigCallback.setAccessible(true);

sConfigCallback.set(null, null);

}

} catch (NoSuchFieldException e) {

if (BuildConfig.DEBUG) {

e.printStackTrace();

}

} catch (ClassNotFoundException e) {

if (BuildConfig.DEBUG) {

e.printStackTrace();

}

} catch (IllegalAccessException e) {

if (BuildConfig.DEBUG) {

e.printStackTrace();

}

}

}

}

}

android webview内存泄漏,Android由webview引起的内存泄漏相关推荐

  1. android webview 内存溢出,Android 内存溢出和内存泄漏的问题

    Android 内存溢出和内存泄漏的问题 在面试中,经常有面试官会问"你知道什么是内存溢出?什么是内存泄漏?怎么避免?"通过这篇文章,你可以回答出来了. 内存溢出(OOM)是指程序 ...

  2. Android性能优化之利用强大的LeakCanary检测内存泄漏及解决办法

    本篇文章主要介绍了Android性能优化之利用LeakCanary检测内存泄漏及解决办法,有兴趣的同学可以了解一下. 目录 前言 什么是内存泄漏? 内存泄漏造成什么影响? 什么是LeakCanary? ...

  3. Android Fragment使用(三) Activity, Fragment, WebView的状态保存和恢复

    Android中的状态保存和恢复 Android中的状态保存和恢复, 包括Activity和Fragment以及其中View的状态处理. Activity的状态除了其中的View和Fragment的状 ...

  4. Android爬坑之旅之WebView

    不知不觉,Hybird App已经成了目前比较主流的一种开发方式. 对于用户体验要求较高或者与硬件交互较多的功能我们一般都会采用Native原生的方式来实现. 而用户交互少,偏展示类,活动类的功能我们 ...

  5. Android开发-WebView中实现Android调用JS JS调用Android 【三】

    老早之前就想总结下Webview相关的知识点了,因为互联网大潮中,很多APP都会使用到Webview,像那些不计其数的电商APP,无一例外的使用Webview:或者一些非电商APP中的像广告页面,注册 ...

  6. WebView深究之Android是如何实现webview初始化的

    webview初始化 关注Android加载webview内核的过程.我们从WebView的init过程中切入. WebView的构造方法,最终都会调用 WebView(Context context ...

  7. WebView Attack In Android : 解析第三方账号登录平台所存在的安全隐患

    转载请注明出处:http://blog.csdn.net/singwhatiwanna/article/details/17663345 前言 这是一个很有趣的话题,WebView在Android中包 ...

  8. android中最新webview的功能,Android WebView实现截长图功能

    本文实例为大家分享了Android实现截长图功能的具体代码,供大家参考,具体内容如下 先看看手机自带的长截屏功能:  机型: vivo x9 plus 大胆推测实现逻辑: 1:需要一个可以滚动的Vie ...

  9. android webview 图片居中,Android WebView实现截长图功能

    本文实例为大家分享了Android实现截长图功能的具体代码,供大家参考,具体内容如下 先看看手机自带的长截屏功能:  机型: vivo x9 plus 大胆推测实现逻辑: 1:需要一个可以滚动的Vie ...

最新文章

  1. js 获取浏览器url参数
  2. 微软中国CTO:不思进取、放弃基本技能的程序员在34.9岁会被淘汰!
  3. 全面学习ORACLE Scheduler特性(5)Schedules调度Programs执行的Jobs
  4. MyBatis中针对if-test的参数为指定值的xml写法
  5. 当年我见过最烂的上网行为审计产品
  6. iview tooltip自动消失_惠州广日自动人行道价格大概多少
  7. 大剑无锋之linux如何查看系统开启了那些端口【面试推荐】
  8. SAP ABAP实用技巧介绍系列之 ABAP XSLT select keyword
  9. Paypal 在线支付接口应用从零开始,第2节,[支付API原理及流程]
  10. Grunt Server:Fatal error: Port 35729 is already in use by another process.
  11. 桌面环境选择_如何在 Ubuntu 20.04 LTS 上安装深度(Deepin)桌面环境 | Linux 中国
  12. java多线程join()方法原理详解
  13. 荣耀9.0系统怎么无需root激活XPOSED框架的教程
  14. Wireshark 基础 | 简介篇
  15. 火车头采集html文档没内容,火车头采集器:编辑任务中常见问题
  16. Could not fetch URL https://pypi.org/simple/selenium/: There was a problem confirming the ssl cer...
  17. python练习题---矩阵求和
  18. 新零售时代下,物流行业迎来新机遇
  19. 利用HTML5新特性实现拖拽交换表格单元格元素
  20. (翻译)Decision-Making in Driver-Automation Shared Control

热门文章

  1. OpenGL之GLFW和glad框架使用(十二)
  2. python之os.path.join
  3. Hls之TS流分离音视频
  4. elementUI中table中自定义修改时间格式2020-10-26T10:00:00
  5. 返回json格式的编写(Msg)
  6. php调用rpc,AMFPHP php远程调用(RPC, Remote Procedure Call)工具 快速入门教程_PHP教程
  7. redistemplate给hash存储设置有效期_客户端较为常用的存储机制
  8. 树莓派 ubuntu gpio_如何给树莓派安装操作系统
  9. csgo躲猫猫模式显示服务器已满,csgo躲猫猫攻略大全
  10. mysql lookup3_mongodb 3.x 之实用新功能窥看[2] ——使用$lookup做多表关联处理