警告handler leaks的解决方法

发现所有的Handler都被打上了"This Handler class should be static or leaks might occur .."的警告, Google一番后发现了解决方法. 


一>, 原因
找到一段E文
Issue: Ensures that Handler classes do not hold on to a reference to an outer class
确保Hanler类不持有外部类的引用
In Android, Handler classes should be static or leaks might occur. Messages enqueued on the application thread's MessageQueue also retain their target Handler. If the Handler is an inner class, its outer class will be retained as well. To avoid leaking the outer class, declare the Handler as a static nested class with a WeakReference to its outer class. 
在Android中, Handler类应是static的, 否则可能会发生泄漏. 程序线程的消息队列的Message也持有对Handler对象的引用. 如果Handler是内部类, 那么(回收内存时)其外部类也会被保留.(使用Handler的Service和Activity就也无法被回收. 这就可能导致内存泄露.) 为了避免泄露其外部类, 可将Handler声明为static并持有其外部类的WeakReference(弱引用).

二>, 解决方法

上面已经指名了一条王道, 将Handler声明为static并持有其外部类的WeakReference(弱引用).

	static class MHandler extends Handler {
		WeakReference outerClass;

		MHandler(OuterClass activity) {
			outerClass = new WeakReference(activity);
		}

		@Override
		public void handleMessage(android.os.Message msg) {
			OuterClass theClass = outerClass.get();
			switch (msg.what) {
			case 0: {
				//使用theClass访问外部类成员和方法
				break;
			}
			default: {
				Log.w(TAG, "未知的Handler Message:" + msg.what);
			}
			}

		}
	}



你可能感兴趣的:(Java,Android)