Last Updated: February 25, 2016
·
544
· dmytrodanylyk

Activities, Threads, & Memory Leaks

Always create Thread & Handler as a static member of your class to prevent memory leak.

static final class MyThread extends Thread {

    @Override
    public void run() {
        // do long operations here
    }
}

If you need reference to outer class use WeakReference.

static final class MyThread2 extends Thread {

    public WeakReference<Activity> reference;

    public MyThread2(Activity reference) {
        this.reference = new WeakReference<Activity>(reference);
    }

    @Override
    public void run() {
        // do long operations here
        Activity activity = reference.get();
        if (activity == null) {
            return;
        }
        // activity.someMethod();
    }
}

More details here.