1. 若何创建一个优先级低的主线程义务,它只会在主线程余暇时才履行,不会影响到app的机能?
至此,核心的内存泄漏检测机制便看完了。
- Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() { @Override public boolean queueIdle() { // do task
- return false; // only once
- }
- });
2. 若何快速创建一个主/子线程handler?
- //主线程handlermainHandler = new Handler(Looper.getMainLooper());//子线程handlerHandlerThread handlerThread = new HandlerThread(“子线程义务”);
- handlerThread.start();
- Handler backgroundHandler = new Handler(handlerThread.getLooper());
- Looper.getMainLooper().getThread() == Thread.currentThread();
可以看到,它起首会向主线程的 MessageQueue 添加一个 IdleHandler 。
System.gc() 可以触发急速 gc 吗?如不雅不可那怎么才能触发即时 gc 呢?
在 LeakCanary 里,须要急速触发 gc,并在之后急速断定弱引用是否被收受接收。这意味着该 gc 必须可以或许急速同步履行。
我们来看下其实现方法:
- /**
- * Indicates to the VM that it would be a good time to run the
- * garbage collector. Note that this is a hint only. There is no guarantee
- * that the garbage collector will actually be run.
- */public static void gc() { boolean shouldRunGC; synchronized(lock) {
- shouldRunGC = justRanFinalization; if (shouldRunGC) {
- justRanFinalization = false;
- } else {
- runGC = true;
- }
- } if (shouldRunGC) {
- Runtime.getRuntime().gc();
- }
- }
注释里清跋扈说了, System.gc() 只是建议垃圾收受接收器来履行收受接收,然则 不克不及包管真的去收受接收 。大年夜代码也能看出,必须先断定 shouldRunGC 才能决定是否真的要 gc。
推荐阅读
Linux 用户可能经常碰到的一个问题是,机械有 16GB 内存之多,运行的过程也不多,然则剩下的 free 内存并不多,大年夜部分都被 buff 和 cache 占用了(比如下面我的 PC)。$ free -h >>>详细阅读
本文标题:带你学开源项目:LeakCanary-如何检测 Activity 是否泄漏
地址:http://www.17bianji.com/lsqh/35385.html
1/2 1