Make your handler a static class.
The warning is a lint warning. You can disable the warning but its a useful info
Here's a list of Lint Check
http://tools.android.com/tips/lint-checks
Quoting from the source @
http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html
Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside.
The solution to this issue is to use a static inner class with a WeakReference
to the outer class, as done in ViewRoot
and its W inner class for instance.
Also check this discussion on android developers group. Check the solution by Romain Guy
https://groups.google.com/forum/#!topic/android-developers/1aPZXZG6kWk
Example from Romain Guy's solution from the above link
class OuterClass {
class InnerClass {
private final WeakReference<OuterClass> mTarget;
InnerClass(OuterClass target) {
mTarget = new WeakReference<OuterClass>(target);
}
void doSomething() {
OuterClass target = mTarget.get();
if (target != null) target.do();
}
Edit:
Example:
public class MainActivity extends Activity {
LinearLayout ll;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = new LinearLayout(this);
new HandlerClass(this);
}
private static class HandlerClass extends Handler{
private final WeakReference<MainActivity> mTarget;
public HandlerClass(MainActivity context)
{
mTarget = new WeakReference<MainActivity>((MainActivity) context);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
MainActivity target = mTarget.get();
if (target != null)
if(msg.what==1){
target.ll.removeAllViews();
// anim.stop();
}
String str = (String) msg.obj;
TextView tv = new TextView(target);
tv.setText(str);
target.ll.setOrientation(LinearLayout.VERTICAL);
target.ll.addView(tv);
//sv.scrollBy(0, 20);
System.out.println(str);
}
};
}
Correct me if the above is wrong or has some issues.
You can also check this blog by Alex Lockwood
http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html