Tutorial by Examples

1. Fix your contexts: Try using the appropriate context: For example since a Toast can be seen in many activities instead of in just one, use getApplicationContext() for toasts, and since services can keep running even though an activity has ended start a service with: Intent myService = new Inten...
A word of caution: AsyncTask has many gotcha's apart from the memory leak described here. So be careful with this API, or avoid it altogether if you don't fully understand the implications. There are many alternatives (Thread, EventBus, RxAndroid, etc). One common mistake with AsyncTask is to c...
Every Time you create an anonymous class, it retains an implicit reference to its parent class. So when you write: public class LeakyActivity extends Activity { ... foo.registerCallback(new BarCallback() { @Override public void onBar() { ...
Often you will want to wrap some of Android's classes in easier to use utility classes. Those utility classes often require a context to access the android OS or your apps' resources. A common example of this is a wrapper for the SharedPreferences class. In order to access Androids shared preference...
LeakCanary is an Open Source Java library to detect memory leaks in your debug builds. Just add the dependencies in the build.gradle: dependencies { debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1' ...
If you implement or create a listener in an Activity, always pay attention to the lifecycle of the object that has the listener registered. Consider an application where we have several different activities/fragments interested in when a user is logged in or out. One way of doing this would be to h...
In android, every developer uses Anonymous Class (Runnable) at least once in a project. Any Anonymous Class has a reference to its parent (activity). If we perform a long-running task, the parent activity will not be destroyed until the task is ended. Example uses handler and Anonymous Runnable cla...

Page 1 of 1