Android fixing memory leaks in legacy code

There are a lot of memory leaks in android applications that were written several years ago without using modern libraries. Fortunately, most of them can be easily fixed without additional dependencies.

Inner AsyncTask leak

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private View someOtherView;

    protected void onCreate(@Nullable Bundle savedInstanceState) {


    private void someMethod() {
        new MyAsyncTask().execute();

    private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... params) {
            some code
            return null;

        protected void onPostExecute(Void aVoid) {

There is a MainActivity memory leak here, because MyAsyncTask class has implicit reference to it, and therefore, MyAsyncTask may prevent MainActivity to be garbage collected (in case if it will outlive activity).
To fix this kind of memory leak, we need to declare MyAsyncTask class with a static keyword. It will help to remove implicit reference to MainActivity. Secondly, to deal with missing references in MyAsyncTask, we should use WeakReference on MainActivity to get them if activity exist:

Android new Throwable().printStackTrace()

Sometimes it’s very hard to navigate through code that you didn’t write. Especially if that code was written a long time ago, and has thousands of lines, and a complex architecture. „Find Usages” option in Android Studio may not help you, and understanding what is going on can be difficult and frustrating. It would be very nice to have a simple mechanism which can show you a stack trace at desired code location. Like while printing exceptions:

Fortunately, we can easily show stack trace at any code location by calling:

Android ripple drawable

Ripple drawable - a drawable that shows a ripple effect in response to state changes.

Rounded corners rectangle

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android=""

        android:clickable="true" />


<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android=""
            <solid android:color="#777" />
            <corners android:radius="20dp" />

Rounded corners rectangle 2