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.
Written by Dmytro
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Android
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#