Garbage Collection causes : MediaPlayer finalized without being released

前端 未结 2 498
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 08:01

After a lot of debugging I finally found what is causing this error! Garbage Collection!

I have a video playing in media view and in the background I am looking for

相关标签:
2条回答
  • 2020-11-29 08:44

    Java GC only manages memory. So when other resources are used (e.g. files, sockets, etc), you need to manually manage them. In the case of MediaPlayer, the documentation mentions that:

    It is also recommended that once a MediaPlayer object is no longer being used, call release() immediately so that resources used by the internal player engine associated with the MediaPlayer object can be released immediately. Resource may include singleton resources such as hardware acceleration components and failure to call release() may cause subsequent instances of MediaPlayer objects to fallback to software implementations or fail altogether.

    So, when you are done with a MediaPlayer instance, you need to make sure you explicitly call release() on that instance. A good place to do this could be in a lifecycle method of the containing Activity, e.g. onDestroy(). Otherwise, when that MediaPlayer instance is eventually garbage collected (at some arbitrary time after you no longer reference it), the finalizer will notice that you never called release() and will output the warning you are seeing.

    0 讨论(0)
  • 2020-11-29 08:48

    I think this is because you create the media player within the scope of the method, therefore, when the method completes, it goes out of scope. This means there are no references, so is ok for garbage collection.

    This means, it can be free'd by the GC before it has even called onCompletion, hence won't release before cleared. Instead, you need to store a reference to the media player as a member variable in your class.

    0 讨论(0)
提交回复
热议问题