Shion のもくログ(旧: Shion の技術メモ)

使った技術のメモや、うまくいかなかった事とかを綴ります

PR

【Android】LeakCanary の導入メモ

概要

Android アプリのメモリリークを検知するには、LeakCanary を導入すると手軽にできます。 Square Open Source 製で、2019年8月現在でも活発に開発されているので、まだまだ安心して使えるかと思われます。 あくまで開発用なので、くれぐれも本番アプリでは使わないようにお気をつけください。

ライセンス

Copyright 2015 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

導入方法

2019年8月末現在では、下記2つのバージョンがあります。 それぞれ微妙に違うので、お気をつけください。

2.x

2.x は下記をアプリモジュールのbuild.gradle に記述するだけで導入できます。

dependencies {
  // debugImplementation because LeakCanary should only run in debug builds.
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-3'
}

変更点はUpgrading to LeakCanary 2 を確認するとわかりやすいかもです。 実装レシピ等はCode recipes - LeakCanary を確認してください。

1.x

手順1

下記をアプリモジュールのbuild.gradle に記述します。

dependencies {
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'
  releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.3'
  // Optional, if you use support library fragments:
  debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.3'
}

手順2

Application クラスを継承した自作Application クラスを用意し、LeakCanary を有効化する記述を追記します。

public class ExampleApplication extends Application {

  @Override public void onCreate() {
    super.onCreate();
    if (LeakCanary.isInAnalyzerProcess(this)) {
      // This process is dedicated to LeakCanary for heap analysis.
      // You should not init your app in this process.
      return;
    }
    LeakCanary.install(this);
    // Normal app init code...
  }
}

使い方

LeakCanary の設定をしたアプリをインストールするだけです。 もし設定したアプリでメモリリークが起きたら、 インストール時に一緒についてくるLeakCanary アプリを起動することで、メモリリーク内容を確認できます。

もし見れなかった場合は、パーミッション設定がうまくできていない可能性があるので、 通知欄やアプリ設定を確認すると良いです。

詳細はFundamentals - LeakCanary をご確認ください。

備考

  • 1.x ではleakcanary-support-fragment を導入することで、Android Support Library のFragment のメモリリーク検知を自動でしてくれるようです
    • 昔はこれが出来なかったので、過去の資料を漁るとFragment のメモリリーク検知をするための実装追加が説明されていたりします
  • 2.x ではAndroidX のFragment ならメモリリーク検知を自動でしてくれるようです

参考文献

PR