├── .gitignore
├── README.md
├── build.gradle
├── fixed-app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── aliasadi
│ │ └── memoryleak
│ │ ├── MainActivity.java
│ │ └── fixed
│ │ ├── AsyncTaskActivity.java
│ │ ├── DownloadListener.java
│ │ ├── HandlerActivity.java
│ │ ├── SingletonActivity.java
│ │ ├── SingletonManager.java
│ │ ├── StaticAsyncTaskActivity.java
│ │ ├── ThreadActivity.java
│ │ └── asynctask
│ │ ├── BestAsyncTaskActivity.java
│ │ └── DownloadTask.java
│ └── res
│ ├── drawable-v24
│ └── ic_launcher_foreground.xml
│ ├── drawable
│ └── ic_launcher_background.xml
│ ├── layout
│ ├── activity_hello_world.xml
│ └── activity_main.xml
│ ├── mipmap-anydpi-v26
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-mdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── leak-app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── aliasadi
│ │ └── memoryleak
│ │ ├── MainActivity.java
│ │ └── leak
│ │ ├── AsyncTaskActivity.java
│ │ ├── DownloadListener.java
│ │ ├── HandlerActivity.java
│ │ ├── SingletonActivity.java
│ │ ├── SingletonManager.java
│ │ ├── StaticAsyncTaskActivity.java
│ │ └── ThreadActivity.java
│ └── res
│ ├── drawable-v24
│ └── ic_launcher_foreground.xml
│ ├── drawable
│ └── ic_launcher_background.xml
│ ├── layout
│ ├── activity_hello_world.xml
│ └── activity_main.xml
│ ├── mipmap-anydpi-v26
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-mdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.png
│ └── ic_launcher_round.png
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── screenshot
├── dump-memory.png
├── fixed-app.png
├── leakcanary.png
├── leaks.png
├── modules.png
├── profiler.png
└── run-app.png
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | *.iml
3 | .gradle
4 | /local.properties
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # avoid-memory-leak-android
2 |
3 | This project is all about shows common patterns of memory leaks in Android development and how to fix them
4 |
5 |
6 | []( https://android-arsenal.com/details/1/6887 )
7 | []( https://proandroiddev.com/everything-you-need-to-know-about-memory-leaks-in-android-d7a59faaf46a )
8 |
9 | #### There is 2 seperated modules:
10 |
11 |
12 |
13 | 1. [leak-app ](https://github.com/AliAsadi/avoid-memory-leak-android/tree/master/leak-app/src/main/java/aliasadi/memoryleak/leak)-> Describe and shows how to cause a leak when we use AsyncTask, Handler, Singleton, Thread.
14 |
15 |
16 | 2. [fixed-app ](https://github.com/AliAsadi/avoid-memory-leak-android/tree/master/fixed-app/src/main/java/aliasadi/memoryleak/fixed)-> Describe and shows how to avoid/fix the leaks
17 |
18 | In Android Studio choose which project you want to run on the top bar.
19 |
20 |
21 |
22 |
23 |
24 |
25 | ## Screenshot
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 | ## How To Avoid Memory Leak?
34 |
35 | 1. Do not keep long-lived references to a context-activity
36 |
37 | ```Java
38 | public static Context context;
39 |
40 | public SampleClass(Activity activity) {
41 | context = (Context) activity;
42 | }
43 | ```
44 |
45 |
46 | 2. Try using the context-application instead of a context-activity
47 |
48 | ```Java
49 | Utils.doSomeLongRunningTask(getApplicationContext());
50 | SingletoneManager.getInstance(getApplicationContext());
51 | ```
52 |
53 | 3. Avoid non-static inner classes
54 |
55 | ```Java
56 | public class MainActivity extends Activity {
57 |
58 | private class DownloadTask extends Thread {
59 | //do some work
60 | }
61 | }
62 | ```
63 |
64 | 4. Avoid strong reference use WeakReference for listeners.
65 |
66 | ```Java
67 | public class DownloadTask extends AsyncTask {
68 |
69 | private WeakReference listener;
70 |
71 | public DownloadTask(DownloadListener listener) {
72 | listener = new WeakReference<>(listener);
73 | }
74 |
75 | @Override
76 | protected Void doInBackground(Void... params) {
77 | ///do some work
78 | }
79 |
80 | @Override
81 | protected void onPostExecute(Void aVoid) {
82 | super.onPostExecute(aVoid);
83 | if (listener.get() != null) {
84 | listener.get().onDownloadTaskDone();
85 | }
86 | }
87 | }
88 | }
89 | ```
90 |
91 | 5. Clean/Stop all your handlers, animation listeners onDestroy()/onStop().
92 |
93 | ```Java
94 | protected void onStop() {
95 | super.onStop();
96 | handler.clearAllMessages();
97 | unregisterReceivers();
98 | view = null;
99 | listener = null;
100 | }
101 | ```
102 |
103 | 6. Avoid Auto-Boxing
104 |
105 | ```Java
106 | public Integer autoBoxing(){
107 | Integer result = 5;
108 | return result;
109 | }
110 | ```
111 |
112 | ```Java
113 | public Integer hiddenAutoBoxing(){
114 | return 5;
115 | }
116 | ```
117 | #### How to avoid Auto-Boxing:
118 |
119 | ```Java
120 | public int autoBoxing(){
121 | int result = 5;
122 | return result;
123 | }
124 | ```
125 |
126 | ```Java
127 | public int hiddenAutoBoxing(){
128 | return 5;
129 | }
130 | ```
131 |
132 | 7. Avoid Auto-Boxing in HashMap - Use SparseArray insead.
133 |
134 | ```Java
135 | public Integer hiddenAutoBoxing(){
136 | HashMap hashMap = new HashMap<>();
137 | hashMap.put(5,"Hi Android Academy");
138 | }
139 | ```
140 |
141 | #### How to avoid Auto-Boxing in HashMap:
142 |
143 | ```Java
144 | public Integer noKeyAutoBoxing(){
145 | SparseArray sparseArray = new SparseArray<>();
146 | sparseArray.put(5,"Hi Android Academy");
147 | }
148 | ```
149 |
150 | ```Java
151 | public Integer noValueAutoBoxing(){
152 | SparseIntArray sparseArray = new SparseIntArray();
153 | sparseArray.put(5,1000);
154 | }
155 | ```
156 |
157 | ## Tools which can help you identify leaks
158 |
159 | * [LeakCanary](https://github.com/square/leakcanary) from Square is a good tool for detecting memory leaks in your app
160 |
161 |
162 |
163 |
164 |
165 | * [Profiler](https://developer.android.com/studio/profile/android-profiler) View the Java heap and memory allocations with Memory Profiler
166 |
167 |
168 |
169 |
170 |
171 | ### License
172 | ```
173 | Copyright (C) 2018 Ali Asadi
174 | Licensed under the Apache License, Version 2.0 (the "License");
175 | you may not use this file except in compliance with the License.
176 | You may obtain a copy of the License at
177 |
178 | http://www.apache.org/licenses/LICENSE-2.0
179 |
180 | Unless required by applicable law or agreed to in writing, software
181 | distributed under the License is distributed on an "AS IS" BASIS,
182 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
183 | See the License for the specific language governing permissions and
184 | limitations under the License.
185 | ```
186 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 |
5 | repositories {
6 | google()
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:3.3.0'
11 |
12 |
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | google()
21 | jcenter()
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/fixed-app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/fixed-app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 | defaultConfig {
6 | applicationId 'aliesaassadi.memoryleak.fixed'
7 | minSdkVersion 19
8 | targetSdkVersion 28
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(dir: 'libs', include: ['*.jar'])
23 | implementation 'com.android.support:appcompat-v7:28.0.0'
24 | implementation 'com.squareup.leakcanary:leakcanary-android:2.7'
25 | }
26 |
--------------------------------------------------------------------------------
/fixed-app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/fixed-app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/MainActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 | import android.support.annotation.Nullable;
6 | import android.view.View;
7 |
8 | import aliasadi.memoryleak.fixed.R;
9 | import aliasadi.memoryleak.fixed.StaticAsyncTaskActivity;
10 | import aliasadi.memoryleak.fixed.AsyncTaskActivity;
11 | import aliasadi.memoryleak.fixed.HandlerActivity;
12 | import aliasadi.memoryleak.fixed.SingletonActivity;
13 | import aliasadi.memoryleak.fixed.ThreadActivity;
14 |
15 | /**
16 | * Created by Ali Asadi on 01/04/2019.
17 | */
18 | public class MainActivity extends Activity implements View.OnClickListener {
19 |
20 | @Override
21 | protected void onCreate(@Nullable Bundle savedInstanceState) {
22 | super.onCreate(savedInstanceState);
23 | setContentView(R.layout.activity_main);
24 |
25 | findViewById(R.id.asyncTask).setOnClickListener(this);
26 | findViewById(R.id.staticAsyncTask).setOnClickListener(this);
27 | findViewById(R.id.thread).setOnClickListener(this);
28 | findViewById(R.id.handler).setOnClickListener(this);
29 | findViewById(R.id.singleton).setOnClickListener(this);
30 | }
31 |
32 | @Override
33 | public void onClick(View v) {
34 | switch (v.getId()) {
35 |
36 | case R.id.asyncTask:
37 | AsyncTaskActivity.start(this);
38 | break;
39 | case R.id.staticAsyncTask:
40 | StaticAsyncTaskActivity.start(this);
41 | break;
42 | case R.id.thread:
43 | ThreadActivity.start(this);
44 | break;
45 | case R.id.handler:
46 | HandlerActivity.start(this);
47 | break;
48 | case R.id.singleton:
49 | SingletonActivity.start(this);
50 | break;
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/AsyncTaskActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.AsyncTask;
7 | import android.os.Bundle;
8 | import android.os.SystemClock;
9 |
10 | import android.widget.TextView;
11 |
12 | import aliasadi.memoryleak.fixed.R;
13 |
14 | /**
15 | * Created by Ali Asadi on 06/02/2018.
16 | */
17 | public class AsyncTaskActivity extends Activity {
18 |
19 | private TextView textView;
20 |
21 | /**
22 | * NOTE : if the task done before rotate/close the activity every thing will be ok without leak.
23 | **/
24 |
25 | @Override
26 | protected void onCreate(Bundle savedInstanceState) {
27 | super.onCreate(savedInstanceState);
28 | setContentView(R.layout.activity_hello_world);
29 | textView = findViewById(R.id.text_view);
30 |
31 | new DownloadTask().execute();
32 | }
33 |
34 | public void updateText() {
35 | textView.setText(R.string.hello);
36 | }
37 |
38 | public static void start(Context context) {
39 | Intent starter = new Intent(context, AsyncTaskActivity.class);
40 | context.startActivity(starter);
41 | }
42 |
43 | /**
44 | * to fix this leak we use static class instead of inner class.
45 | * static class does not have reference to the containing activity class
46 | **/
47 | private static class DownloadTask extends AsyncTask {
48 |
49 | @Override
50 | protected Void doInBackground(Void... params) {
51 | SystemClock.sleep(2000 * 10);
52 | return null;
53 | }
54 |
55 | /**
56 | * Problem:
57 | * we still need a reference to activity or listener to run the updateText() method
58 | * what we should do? go to the next example at @StaticAsyncTask class to know how
59 | * to deal with this issue.
60 | **/
61 | @Override
62 | protected void onPostExecute(Void aVoid) {
63 | super.onPostExecute(aVoid);
64 | //updateText();
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/DownloadListener.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed;
2 |
3 | /**
4 | * Created by Ali Asadi on 2019-05-29.
5 | */
6 | public interface DownloadListener {
7 | void onDownloadTaskDone();
8 | }
9 |
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/HandlerActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 | import android.os.Handler;
8 | import android.os.Message;
9 |
10 | import android.util.Log;
11 |
12 | import aliasadi.memoryleak.fixed.R;
13 |
14 | /**
15 | * Created by Ali Asadi on 06/02/2018.
16 | */
17 | public class HandlerActivity extends Activity {
18 |
19 | private final DownloadTask downloadTask = new DownloadTask();
20 |
21 | /**
22 | * The handler attached to the main thread
23 | **/
24 | private final Handler handler = new TaskHandler();
25 |
26 | @Override
27 | protected void onCreate(Bundle savedInstanceState) {
28 | super.onCreate(savedInstanceState);
29 | setContentView(R.layout.activity_hello_world);
30 |
31 | /**
32 | * Post a message and delay its execution for 10 minutes.
33 | *
34 | * that's mean post a message to the queue, to be run after the specified amount of time elapses,
35 | * The downloadTask will be run on the thread to which this handler is attached on (MainThread)
36 | * **/
37 | handler.postDelayed(downloadTask, 1000 * 60 * 10);
38 | }
39 |
40 | @Override
41 | protected void onDestroy() {
42 | super.onDestroy();
43 |
44 | /**
45 | * Remove any pending posts of Runnable @downloadTask that
46 | * are in the message queue, ot prevent leak.
47 | * **/
48 | handler.removeCallbacks(downloadTask);
49 | }
50 |
51 | public static void start(Context context) {
52 | Intent starter = new Intent(context, HandlerActivity.class);
53 | context.startActivity(starter);
54 | }
55 |
56 | /**
57 | * Use static class instead of inner class.
58 | * static class does not have reference to the containing activity
59 | **/
60 | private static class DownloadTask implements Runnable {
61 | @Override
62 | public void run() {
63 | Log.e("HandlerActivity", "in run()");
64 | }
65 | }
66 |
67 | /**
68 | * Use static class instead of inner class.
69 | * static class does not have reference to the containing activity
70 | **/
71 | private static class TaskHandler extends Handler {
72 | @Override
73 | public void handleMessage(Message msg) {
74 | Log.e("HandlerActivity", "handle message");
75 | }
76 | }
77 |
78 | }
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/SingletonActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 |
8 | import aliasadi.memoryleak.fixed.R;
9 |
10 | /**
11 | * Created by Ali Asadi on 06/02/2018.
12 | */
13 | public class SingletonActivity extends Activity {
14 |
15 | @Override
16 | protected void onCreate(Bundle savedInstanceState) {
17 | super.onCreate(savedInstanceState);
18 | setContentView(R.layout.activity_hello_world);
19 |
20 | /**
21 | * Using application context instead (Take a a look at the @SingletonManager).
22 | * **/
23 | SingletonManager.getInstance(this);
24 | }
25 |
26 | public static void start(Context context) {
27 | Intent starter = new Intent(context, SingletonActivity.class);
28 | context.startActivity(starter);
29 | }
30 |
31 | }
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/SingletonManager.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | * Created by Ali Asadi on 13/02/2018.
7 | */
8 | public class SingletonManager {
9 |
10 | private static SingletonManager singleton;
11 | private Context context;
12 |
13 | private SingletonManager(Context context) {
14 | this.context = context;
15 | }
16 |
17 | public synchronized static SingletonManager getInstance(Context context) {
18 | if (singleton == null) {
19 | /**
20 | * Use application Context to prevent leak.
21 | * **/
22 | singleton = new SingletonManager(context.getApplicationContext());
23 | }
24 | return singleton;
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/StaticAsyncTaskActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.AsyncTask;
7 | import android.os.Bundle;
8 | import android.os.SystemClock;
9 |
10 | import android.widget.TextView;
11 |
12 | import java.lang.ref.WeakReference;
13 |
14 | /**
15 | * Created by Ali Asadi on 06/02/2018.
16 | */
17 | public class StaticAsyncTaskActivity extends Activity implements DownloadListener {
18 |
19 | /**
20 | * Weak Reference Description:
21 | *
22 | * Weak reference objects, which do not prevent their referents from being
23 | * made finalizable, finalized, and then reclaimed.
24 | *
25 | * Suppose that the garbage collector determines at a certain point in time that an
26 | * object is weakly reachable.
27 | * At that time it will atomically clear all weak references to that object and all
28 | * weak references to any other weakly-reachable
29 | * objects from which that object is reachable through a chain of strong and soft references.
30 | * At the same time it will declare all of the formerly weakly-reachable objects to be
31 | * finalizable. At the same time or at some later time it will enqueue
32 | * those newly-cleared weak references that are registered with reference queues.
33 | *
34 | * MORE -> https://developer.android.com/reference/java/lang/ref/WeakReference.html
35 | **/
36 |
37 | private TextView textView;
38 |
39 | @Override
40 | protected void onCreate(Bundle savedInstanceState) {
41 | super.onCreate(savedInstanceState);
42 | setContentView(R.layout.activity_hello_world);
43 | textView = findViewById(R.id.text_view);
44 |
45 | new DownloadTask(this).execute();
46 | }
47 |
48 | public static void start(Context context) {
49 | Intent starter = new Intent(context, StaticAsyncTaskActivity.class);
50 | context.startActivity(starter);
51 | }
52 |
53 | @Override
54 | public void onDownloadTaskDone() {
55 | updateText();
56 | }
57 |
58 | public void updateText() {
59 | textView.setText(R.string.hello);
60 | }
61 |
62 | private static class DownloadTask extends AsyncTask {
63 |
64 | /**
65 | * The WeakReference allows the Activity to be garbage collected.
66 | * garbage collected does not protect the weak reference from begin reclaimed.
67 | **/
68 | private WeakReference listener;
69 |
70 | private DownloadTask(DownloadListener activity) {
71 | this.listener = new WeakReference<>(activity);
72 | }
73 |
74 | @Override
75 | protected Void doInBackground(Void... params) {
76 | SystemClock.sleep(2000 * 10);
77 | return null;
78 | }
79 |
80 | @Override
81 | protected void onPostExecute(Void aVoid) {
82 | super.onPostExecute(aVoid);
83 | if (listener.get() != null) {
84 | listener.get().onDownloadTaskDone();
85 | }
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/ThreadActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 | import android.os.SystemClock;
8 |
9 |
10 | import aliasadi.memoryleak.fixed.R;
11 |
12 | /**
13 | * Created by Ali Asadi on 06/02/2018.
14 | */
15 | public class ThreadActivity extends Activity {
16 |
17 | /**
18 | * if the task done before to move to another activity
19 | * or rotate the device every thing will works fine with out leak.
20 | * **/
21 |
22 | private DownloadTask thread = new DownloadTask();
23 |
24 | @Override
25 | protected void onCreate(Bundle savedInstanceState) {
26 | super.onCreate(savedInstanceState);
27 | setContentView(R.layout.activity_hello_world);
28 |
29 | thread.start();
30 | }
31 |
32 | @Override
33 | protected void onDestroy() {
34 | super.onDestroy();
35 |
36 | /**
37 | * Interrupts/stops this thread.
38 | * **/
39 | thread.interrupt();
40 | }
41 |
42 | public static void start(Context context) {
43 | Intent starter = new Intent(context, ThreadActivity.class);
44 | context.startActivity(starter);
45 | }
46 |
47 | /**
48 | * make it static so it does not have referenced to the containing activity class
49 | * **/
50 | private static class DownloadTask extends Thread {
51 | @Override
52 | public void run() {
53 | while (!isInterrupted()) {
54 | SystemClock.sleep(2000 * 10);
55 | }
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/asynctask/BestAsyncTaskActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed.asynctask;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 |
6 | import android.widget.TextView;
7 |
8 | import aliasadi.memoryleak.fixed.DownloadListener;
9 | import aliasadi.memoryleak.fixed.R;
10 |
11 | /**
12 | * Created by Ali Asadi on 06/02/2018.
13 | */
14 | public class BestAsyncTaskActivity extends Activity implements DownloadListener {
15 |
16 | /**
17 | * NOTE : if the task done before rotate/close the activity every thing will be ok without leak.
18 | **/
19 |
20 | private TextView textView;
21 | private DownloadTask downloadTask;
22 |
23 | @Override
24 | protected void onCreate(Bundle savedInstanceState) {
25 | super.onCreate(savedInstanceState);
26 | setContentView(R.layout.activity_hello_world);
27 | textView = findViewById(R.id.text_view);
28 | downloadTask = new DownloadTask(this);
29 | }
30 |
31 | @Override
32 | protected void onDestroy() {
33 | super.onDestroy();
34 | /**
35 | * cancel the task so it will no invoke onPostExecute().
36 | * **/
37 | downloadTask.cancel(true);
38 | }
39 |
40 | @Override
41 | public void onDownloadTaskDone() {
42 | updateText();
43 | }
44 |
45 | public void updateText() {
46 | textView.setText(R.string.hello);
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/fixed-app/src/main/java/aliasadi/memoryleak/fixed/asynctask/DownloadTask.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.fixed.asynctask;
2 |
3 | import android.os.AsyncTask;
4 | import android.os.SystemClock;
5 |
6 | import java.lang.ref.WeakReference;
7 |
8 | import aliasadi.memoryleak.fixed.DownloadListener;
9 |
10 | /**
11 | * Created by Ali Asadi on 06/02/2018.
12 | */
13 | public class DownloadTask extends AsyncTask {
14 |
15 | /**
16 | * The WeakReference allows the Activity to be garbage collected.
17 | * garbage collected dose not protect the weak reference from begin reclaimed.
18 | **/
19 | private WeakReference listener;
20 |
21 | public DownloadTask(DownloadListener listener) {
22 | this.listener = new WeakReference<>(listener);
23 | }
24 |
25 | @Override
26 | protected Void doInBackground(Void... params) {
27 | /**
28 | * Check if cancelled.
29 | * **/
30 | while (!isCancelled()) {
31 | SystemClock.sleep(2000 * 10);
32 | }
33 | return null;
34 | }
35 |
36 | @Override
37 | protected void onPostExecute(Void aVoid) {
38 | super.onPostExecute(aVoid);
39 | if (listener.get() != null) {
40 | listener.get().onDownloadTaskDone();
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/fixed-app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/fixed-app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/fixed-app/src/main/res/layout/activity_hello_world.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/fixed-app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
17 |
18 |
24 |
25 |
31 |
32 |
38 |
39 |
45 |
46 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/fixed-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/fixed-app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/fixed-app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Memory-Fixed
3 | Hello, Leak!
4 |
5 |
--------------------------------------------------------------------------------
/fixed-app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Apr 01 19:27:30 IDT 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/leak-app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/leak-app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 |
6 |
7 | defaultConfig {
8 | applicationId 'aliesaassadi.memoryleak.leak'
9 | minSdkVersion 19
10 | targetSdkVersion 28
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 |
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: 'libs', include: ['*.jar'])
29 |
30 | implementation 'com.squareup.leakcanary:leakcanary-android:2.7'
31 |
32 | implementation 'com.android.support:appcompat-v7:28.0.0'
33 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
34 | testImplementation 'junit:junit:4.12'
35 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
36 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
37 | }
38 |
--------------------------------------------------------------------------------
/leak-app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/leak-app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/leak-app/src/main/java/aliasadi/memoryleak/MainActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 | import android.support.annotation.Nullable;
6 | import android.view.View;
7 |
8 | import aliasadi.memoryleak.leak.R;
9 |
10 | import aliasadi.memoryleak.leak.AsyncTaskActivity;
11 | import aliasadi.memoryleak.leak.HandlerActivity;
12 | import aliasadi.memoryleak.leak.SingletonActivity;
13 | import aliasadi.memoryleak.leak.StaticAsyncTaskActivity;
14 | import aliasadi.memoryleak.leak.ThreadActivity;
15 |
16 | /**
17 | * Created by Ali Asadi on 01/04/2019.
18 | */
19 | public class MainActivity extends Activity implements View.OnClickListener {
20 |
21 | @Override
22 | protected void onCreate(@Nullable Bundle savedInstanceState) {
23 | super.onCreate(savedInstanceState);
24 | setContentView(R.layout.activity_main);
25 |
26 | findViewById(R.id.asyncTask).setOnClickListener(this);
27 | findViewById(R.id.staticAsyncTask).setOnClickListener(this);
28 | findViewById(R.id.thread).setOnClickListener(this);
29 | findViewById(R.id.handler).setOnClickListener(this);
30 | findViewById(R.id.singleton).setOnClickListener(this);
31 | }
32 |
33 | @Override
34 | public void onClick(View v) {
35 | switch (v.getId()) {
36 |
37 | case R.id.asyncTask:
38 | AsyncTaskActivity.start(this);
39 | break;
40 | case R.id.staticAsyncTask:
41 | StaticAsyncTaskActivity.start(this);
42 | break;
43 | case R.id.thread:
44 | ThreadActivity.start(this);
45 | break;
46 | case R.id.handler:
47 | HandlerActivity.start(this);
48 | break;
49 | case R.id.singleton:
50 | SingletonActivity.start(this);
51 | break;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/leak-app/src/main/java/aliasadi/memoryleak/leak/AsyncTaskActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.leak;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.Activity;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.os.AsyncTask;
8 | import android.os.Bundle;
9 | import android.os.SystemClock;
10 | import android.widget.TextView;
11 |
12 | import aliasadi.memoryleak.leak.R;
13 |
14 | /**
15 | * Created by Ali Asadi on 06/02/2018.
16 | */
17 | public class AsyncTaskActivity extends Activity {
18 |
19 | /**
20 | * We will have memory leaks when we rotate/close the activity within 20 seconds after it’s created.
21 | * Since the AsyncTask is declared as non-static class it will hold the reference of
22 | * the activity which made the activity not eligible for garbage collection.
23 | *
24 | * NOTE : if the task done before rotate/close the activity every thing will be ok without leak.
25 | * **/
26 |
27 | private TextView textView;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_hello_world);
33 | textView = findViewById(R.id.text_view);
34 |
35 | new DownloadTask().execute();
36 | }
37 |
38 | public static void start(Context context) {
39 | Intent starter = new Intent(context, AsyncTaskActivity.class);
40 | context.startActivity(starter);
41 | }
42 |
43 | public void updateText() {
44 | textView.setText(R.string.hello);
45 | }
46 |
47 | @SuppressLint("StaticFieldLeak")
48 | private class DownloadTask extends AsyncTask {
49 |
50 | @Override
51 | protected Void doInBackground(Void... params) {
52 | SystemClock.sleep(2000 * 10);
53 | return null;
54 | }
55 |
56 | @Override
57 | protected void onPostExecute(Void aVoid) {
58 | super.onPostExecute(aVoid);
59 |
60 | try {
61 | updateText();
62 | } catch (Exception e) {
63 | //doNothing
64 | }
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/leak-app/src/main/java/aliasadi/memoryleak/leak/DownloadListener.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.leak;
2 |
3 | /**
4 | * Created by Ali Asadi on 2019-05-29.
5 | */
6 | public interface DownloadListener {
7 | void onDownloadTaskDone();
8 | }
9 |
--------------------------------------------------------------------------------
/leak-app/src/main/java/aliasadi/memoryleak/leak/HandlerActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.leak;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.Activity;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.os.Bundle;
8 | import android.os.Handler;
9 | import android.os.Message;
10 | import android.util.Log;
11 |
12 | import aliasadi.memoryleak.leak.R;
13 |
14 | /**
15 | * Created by Ali Asadi on 06/02/2018.
16 | */
17 | public class HandlerActivity extends Activity {
18 |
19 | /**
20 | * Since this Handler is declared as an inner class,
21 | * it may prevent the outer class from being garbage collected.
22 | *
23 | * NOTE: The handler attached to the main thread
24 | * **/
25 | @SuppressLint("HandlerLeak")
26 | private final Handler handler = new Handler() {
27 | @Override
28 | public void handleMessage(Message msg) {
29 | Log.e("HandlerActivity", "new message");
30 | }
31 | };
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 | setContentView(R.layout.activity_hello_world);
37 |
38 | /**
39 | * Post a message and delay its execution for 10 minutes.
40 | *
41 | * that's mean post a message to the queue, to be run after the specified amount of time elapses,
42 | * The downloadTask will be run on the thread to which this handler is attached on (MainThread)
43 | * **/
44 | handler.postDelayed(new Runnable() {
45 | @Override
46 | public void run() {
47 | Log.e("HandlerActivity", "task start");
48 | }
49 | }, 1000 * 60 * 10);
50 | }
51 |
52 | public static void start(Context context) {
53 | Intent starter = new Intent(context, HandlerActivity.class);
54 | context.startActivity(starter);
55 | }
56 |
57 | }
--------------------------------------------------------------------------------
/leak-app/src/main/java/aliasadi/memoryleak/leak/SingletonActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.leak;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 |
8 | import aliasadi.memoryleak.leak.R;
9 |
10 | /**
11 | * Created by Ali Asadi on 06/02/2018.
12 | */
13 | public class SingletonActivity extends Activity {
14 |
15 | @Override
16 | protected void onCreate(Bundle savedInstanceState) {
17 | super.onCreate(savedInstanceState);
18 | setContentView(R.layout.activity_hello_world);
19 |
20 | /**
21 | * Passing a activity as a context to the singleton!
22 | * take a look at @SingletonManager class.
23 | * **/
24 | SingletonManager.getInstance(this);
25 | }
26 |
27 | public static void start(Context context) {
28 | Intent starter = new Intent(context, SingletonActivity.class);
29 | context.startActivity(starter);
30 | }
31 | }
--------------------------------------------------------------------------------
/leak-app/src/main/java/aliasadi/memoryleak/leak/SingletonManager.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.leak;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | * Created by Ali Asadi on 13/02/2018.
7 | */
8 | public class SingletonManager {
9 |
10 | private static SingletonManager singleton;
11 | private Context context;
12 |
13 | private SingletonManager(Context context) {
14 | this.context = context;
15 | }
16 |
17 | public synchronized static SingletonManager getInstance(Context context) {
18 | if (singleton == null) {
19 | /**
20 | * Saving the activity context. Leak!
21 | * the activity will stack in the memory until the end of the application.
22 | * **/
23 | singleton = new SingletonManager(context);
24 | }
25 | return singleton;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/leak-app/src/main/java/aliasadi/memoryleak/leak/StaticAsyncTaskActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.leak;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.Activity;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.os.AsyncTask;
8 | import android.os.Bundle;
9 | import android.os.SystemClock;
10 | import android.widget.TextView;
11 |
12 | /**
13 | * Created by Ali Asadi on 06/02/2018.
14 | */
15 | public class StaticAsyncTaskActivity extends Activity implements DownloadListener {
16 | private TextView textView;
17 |
18 | /**
19 | * NOTE : if the task done before rotate/close the listener every thing will be ok without leak.
20 | * **/
21 |
22 | @Override
23 | protected void onCreate(Bundle savedInstanceState) {
24 | super.onCreate(savedInstanceState);
25 | setContentView(R.layout.activity_hello_world);
26 | textView = findViewById(R.id.text_view);
27 |
28 | new DownloadTask(this).execute();
29 | }
30 |
31 | public static void start(Context context) {
32 | Intent starter = new Intent(context, StaticAsyncTaskActivity.class);
33 | context.startActivity(starter);
34 | }
35 |
36 | public void updateText() {
37 | textView.setText(R.string.hello);
38 | }
39 |
40 | @Override
41 | public void onDownloadTaskDone() {
42 | updateText();
43 | }
44 |
45 | private static class DownloadTask extends AsyncTask {
46 |
47 | /**
48 | * Saving a strong reference of the listener, which made
49 | * the listener not eligible for garbage collection.
50 | * **/
51 | @SuppressLint("StaticFieldLeak")
52 | private DownloadListener listener;
53 |
54 | public DownloadTask(DownloadListener listener) {
55 | this.listener = listener;
56 | }
57 |
58 | @Override
59 | protected Void doInBackground(Void... params) {
60 | SystemClock.sleep(2000 * 10);
61 | return null;
62 | }
63 |
64 | @Override
65 | protected void onPostExecute(Void aVoid) {
66 | super.onPostExecute(aVoid);
67 | try {
68 | listener.onDownloadTaskDone();
69 | } catch (Exception e) {
70 | //doNothing
71 | }
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/leak-app/src/main/java/aliasadi/memoryleak/leak/ThreadActivity.java:
--------------------------------------------------------------------------------
1 | package aliasadi.memoryleak.leak;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 | import android.os.SystemClock;
8 |
9 | import aliasadi.memoryleak.leak.R;
10 |
11 | /**
12 | * Created by Ali Asadi on 06/02/2018.
13 | */
14 | public class ThreadActivity extends Activity {
15 |
16 | /**
17 | * We will have memory leaks when we rotate/close the activity within 20 seconds after it’s created.
18 | * Since the AsyncTask is declared as non-static class it will hold the reference of
19 | * the activity which made the activity not eligible for garbage collection.
20 | *
21 | * NOTE : if the task done before rotate/close the activity every thing will be ok without leak.
22 | * **/
23 |
24 | @Override
25 | protected void onCreate(Bundle savedInstanceState) {
26 | super.onCreate(savedInstanceState);
27 | setContentView(R.layout.activity_hello_world);
28 |
29 | new DownloadTask().start();
30 | }
31 |
32 | public static void start(Context context) {
33 | Intent starter = new Intent(context, ThreadActivity.class);
34 | context.startActivity(starter);
35 | }
36 |
37 | /**
38 | * non-static anonymous classes hold an implicit reference to their enclosing class.
39 | ***/
40 | private class DownloadTask extends Thread {
41 | @Override
42 | public void run() {
43 | SystemClock.sleep(2000 * 10);
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/leak-app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/leak-app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/leak-app/src/main/res/layout/activity_hello_world.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/leak-app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
17 |
18 |
24 |
25 |
31 |
32 |
38 |
39 |
45 |
46 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/leak-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/leak-app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/leak-app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Memory-Leak
3 | Hello, Leak!
4 |
5 |
--------------------------------------------------------------------------------
/leak-app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/screenshot/dump-memory.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/screenshot/dump-memory.png
--------------------------------------------------------------------------------
/screenshot/fixed-app.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/screenshot/fixed-app.png
--------------------------------------------------------------------------------
/screenshot/leakcanary.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/screenshot/leakcanary.png
--------------------------------------------------------------------------------
/screenshot/leaks.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/screenshot/leaks.png
--------------------------------------------------------------------------------
/screenshot/modules.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/screenshot/modules.png
--------------------------------------------------------------------------------
/screenshot/profiler.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/screenshot/profiler.png
--------------------------------------------------------------------------------
/screenshot/run-app.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AliAsadi/avoid-memory-leak-android/e618e175bdfbce6d55f21558045129896fbf7c9e/screenshot/run-app.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':fixed-app', ':leak-app'
2 |
--------------------------------------------------------------------------------