泄漏金丝雀在MediaBrowserServiceCompat示例应用程序中检测到内存泄漏

时间:2019-12-10 09:29:11

标签: android memory-leaks android-service leakcanary mediabrowserservice

我创建了一个实现MediaBrowserServiceCompat的测试应用。我遵循了该指南: https://developer.android.com/guide/topics/media-apps/audio-app/building-a-mediabrowserservice 创建了MediaPlaybackService和MainActivity。我在onDestroy方法中添加了泄漏金丝雀,并添加了AppWatcher.objectWatcher.watch(this)。打开和退出应用程序时,泄漏金丝雀会发现泄漏:

6153 bytes retained
    ┬
    ├─ android.service.media.MediaBrowserService$ServiceBinder
    │    Leaking: UNKNOWN
    │    GC Root: Global variable in native code
    │    ↓ MediaBrowserService$ServiceBinder.this$0
    │                                        ~~~~~~
    ├─ androidx.media.MediaBrowserServiceCompat$MediaBrowserServiceImplApi26$MediaBrowserServiceApi26
    │    Leaking: UNKNOWN
    │    MediaBrowserServiceCompat$MediaBrowserServiceImplApi26$MediaBrowserServiceApi26 does not wrap an activity context
    │    ↓ MediaBrowserServiceCompat$MediaBrowserServiceImplApi26$MediaBrowserServiceApi26.mBase
    │                                                                                      ~~~~~
    ╰→ com.example.mediabrowsertestapp.MediaPlaybackService
    ​     Leaking: YES (ObjectWatcher was watching this)
    ​     MediaPlaybackService does not wrap an activity context
    ​     key = 11f40383-1498-4743-9f20-208cbd2839a1
    ​     watchDurationMillis = 5191
    ​     retainedDurationMillis = 183

Please include this in bug reports and Stack Overflow questions.

    Build.VERSION.SDK_INT: 28
    Build.MANUFACTURER: HMD Global
    LeakCanary version: 2.0
    App process name: com.example.mediabrowsertestapp
    Analysis duration: 8967 ms
    Heap dump file path: /data/user/0/com.example.mediabrowsertestapp/files/leakcanary/2019-12-10_10-21-47_693.hprof
    Heap dump timestamp: 1575969720525

由于该应用仅包含来自google示例的代码,因此我不知道如何处理此泄漏。我应该忽略它吗?

代码: https://github.com/finneapps/MediaBrowserService-memory-leak

package com.example.mediabrowsertestapp

import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.media.MediaBrowserServiceCompat
import leakcanary.AppWatcher

private const val LOG_TAG = "MediaPlaybackService"

class MediaPlaybackService : MediaBrowserServiceCompat() {

    private var mediaSession: MediaSessionCompat? = null
    private lateinit var stateBuilder: PlaybackStateCompat.Builder

    override fun onCreate() {
        super.onCreate()
        mediaSession = MediaSessionCompat(baseContext, LOG_TAG).apply {
            setFlags(
                MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                        or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
            )
            stateBuilder = PlaybackStateCompat.Builder()
                .setActions(
                    PlaybackStateCompat.ACTION_PLAY
                            or PlaybackStateCompat.ACTION_PLAY_PAUSE
                )
            setPlaybackState(stateBuilder.build())
            setSessionToken(sessionToken)
        }
    }

    override fun onGetRoot(
        clientPackageName: String, clientUid: Int,
        rootHints: Bundle?
    ): BrowserRoot? {
        return BrowserRoot(LOG_TAG, null)
    }

    override fun onLoadChildren(
        parentMediaId: String,
        result: Result<List<MediaBrowserCompat.MediaItem>>
    ) {
        result.sendResult(emptyList())
    }

    override fun onDestroy() {
        super.onDestroy()
        AppWatcher.objectWatcher.watch(this)
    }
}
package com.example.mediabrowsertestapp

import android.content.ComponentName
import android.media.AudioManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat

class MainActivity : AppCompatActivity() {
    private val controllerCallback = object : MediaControllerCompat.Callback() {

        override fun onMetadataChanged(metadata: MediaMetadataCompat?) {}

        override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {}
    }

    private lateinit var mediaBrowser: MediaBrowserCompat

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mediaBrowser = MediaBrowserCompat(
            this,
            ComponentName(this, MediaPlaybackService::class.java),
            connectionCallbacks,
            null 
        )
    }

    override fun onStart() {
        super.onStart()
        mediaBrowser.connect()
    }

    override fun onResume() {
        super.onResume()
        volumeControlStream = AudioManager.STREAM_MUSIC
    }

    override fun onStop() {
        super.onStop()
        MediaControllerCompat.getMediaController(this)?.unregisterCallback(controllerCallback)
        mediaBrowser.disconnect()
    }

    private val connectionCallbacks = object : MediaBrowserCompat.ConnectionCallback() {
        override fun onConnected() {
            mediaBrowser.sessionToken.also { token ->
                val mediaController = MediaControllerCompat(
                    this@MainActivity, // Context
                    token
                )
                MediaControllerCompat.setMediaController(this@MainActivity, mediaController)
            }

        }

        override fun onConnectionSuspended() {

        }

        override fun onConnectionFailed() {

        }
    }
}
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.mediabrowsertestapp"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "androidx.media:media:1.1.0"
    debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

1 个答案:

答案 0 :(得分:2)

您的媒体服务扩展了MediaBrowserServiceCompat。最初,这看起来像是MediaBrowserServiceCompat的问题。 androidx.media:media:1.1.0是最新版本,MediaBrowserServiceCompat的最新资源当前为here

MediaBrowserServiceCompat是一个基础服务类,它委托给AOSP MediaBrowserService类(sources)的子类。有点棘手的是,尽管MediaBrowserService是一种服务,但当由MediaBrowserServiceCompat使用时,它实际上并不是作为真正的Android服务创建的,而是作为MediaBrowserServiceCompat传递回调到的纯粹的委托创建的。这本身就意味着容易出错。

MediaBrowserService子类保存对MediaBrowserServiceCompat实例的引用,以便t

泄漏跟踪显示存在对MediaBrowserService $ ServiceBinder的本地引用。当MediaBrowserServiceCompat收到其onBind()调用时,它将从MediaBrowserService返回绑定程序。只要MediaBrowserServiceCompat处于活动状态,就应保留该活页夹,并在销毁销毁该活页夹时将其释放。此时,我们需要进行堆转储以进一步挖掘。

我下载了源代码,构建了应用程序,并将其部署在仿真器(API 29)上,并能够通过按回来重现泄漏。我注意到MediaSessionCompat构造函数javadoc指出“会话结束时必须调用{@link #release()}”。我尝试在onDestroy()中调用它,但仍然会发生泄漏。

我想知道这是否仅发生在应用程序兼容或AOSP中。我将代码移植回AOSP(无兼容性),并且发生了相同的事情。

┬
├─ android.service.media.MediaBrowserService$ServiceBinder
│    Leaking: UNKNOWN
│    GC Root: Global variable in native code
│    ↓ MediaBrowserService$ServiceBinder.this$0
│                                        ~~~~~~
╰→ com.example.mediabrowsertestapp.MediaPlaybackService
​     Leaking: YES (ObjectWatcher was watching this)
​     MediaPlaybackService2 does not wrap an activity context
​     key = e9c30a2e-e06e-4c4b-b375-f8c8c1482761
​     watchDurationMillis = 5214
​     retainedDurationMillis = 179

METADATA

Build.VERSION.SDK_INT: 25
Build.MANUFACTURER: Google
LeakCanary version: 2.0
App process name: com.example.mediabrowsertestapp
Analysis duration: 2159 ms

我尽可能地删除了代码,然后发现泄漏仍在发生。这是最终的代码:

class MediaPlaybackService : MediaBrowserService() {

    override fun onLoadChildren(
        parentId: String,
        result: Result<MutableList<MediaBrowser.MediaItem>>
    ) {
        result.sendResult(mutableListOf())
    }

    override fun onGetRoot(
        clientPackageName: String, clientUid: Int,
        rootHints: Bundle?
    ): BrowserRoot? {
        return BrowserRoot("MediaPlaybackService", null)
    }


    override fun onDestroy() {
        super.onDestroy()
        AppWatcher.objectWatcher.watch(this)
    }
}
class MainActivity : Activity() {
    private lateinit var mediaBrowser: MediaBrowser

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mediaBrowser = MediaBrowser(
            this,
            ComponentName(this, MediaPlaybackService::class.java),
            connectionCallbacks,
            null
        )
    }

    override fun onStart() {
        super.onStart()
        mediaBrowser.connect()
    }

    override fun onStop() {
        super.onStop()
        mediaBrowser.disconnect()
    }

    private val connectionCallbacks = object : MediaBrowser.ConnectionCallback() {
        override fun onConnected() {
        }

        override fun onConnectionSuspended() {

        }

        override fun onConnectionFailed() {

        }
    }
}

这可能是针对最新Android版本的一个问题,即使它已经存在了一段时间。根据设计,进程间的调用会导致绑定程序在内存中的保留时间长于发生的时间。当MediaBrowserService被销毁时,MediaBrowserService.ServiceBinder应该释放对其外部类MediaBrowserService的引用。

以下是在AOSP中复制它的PR:https://github.com/finneapps/MediaBrowserService-memory-leak/pull/1