关于Android VideoView导致的内存泄漏的问题

来源:互联网 发布:淘宝药店七乐康 假 编辑:程序博客网 时间:2024/06/05 08:11

今天在用leakcanary测试项目的时候,无意中在用VideoView播放本地视频时,出现内存泄漏问题,提示是AudioManager类出现的, 后面百思不得其解,因为代码中Context没有被长生命周期的所引用,为什么还会出现泄漏呢?后面通过google才发现原来是setVideoPath()导致的,VideoView内部的AudioManager会对Activity持有一个强引用,而AudioManager的生命周期比较长,导致这个Activity始终无法被回收,这个bug直到2015年5月才被谷歌修复。

后面也相应的找到了解决方法,需要重写如下方法

@Overrideprotected void attachBaseContext(Context newBase) {    super.attachBaseContext(new ContextWrapper(newBase) {        @Override        public Object getSystemService(String name) {            if (Context.AUDIO_SERVICE.equals(name))                return getApplicationContext().getSystemService(name);            return super.getSystemService(name);        }    });}
就能完美解决此问题,不得不说谷歌真强大。

0 0
原创粉丝点击