Y R U !working
I’m currently developing simple app (my first real, or rather “real”) on Android. Lyrics. It’ll display lyrics for currently playing song, and (ofc) it will have option to manually search lyrics for some artists.
I have stumbled upon this piece of deprecated code (look@picture above), which was written for
which is 2.3.3, 2.3.4 Android version. Quite old. So i commented that line in build.gradle and write
Nice, now we can write some decent code!
Ok, but what about that lint in Android Studio? In other words: “In Android, Handler classes should be static or leaks might occur.” In this code sample I extend Service class. If handler is not static, my Service cannot be garbage collected, even after being destroyed. And in longer operations, this may lead to memory leak.
There are four different degrees of reference strength, and three of them are widely popular.
StringBuffer buffer = new StringBuffer();
creates a new
StringBuffer() and stores a strong reference to it in the variable
buffer. For object reachable via strong reference, its not eligible for garbage collection. Which is what we want in everyday java code, IMO.
myClassWeakReference = new WeakReference<>(myClassInstance);
A weak reference, is a reference that isn’t strong enough to force an object to remain in memory. So with sample above, later, in code, when you use myClassWeakReference.get(), chances are that you can get null.
This is not much of an issue unless you post long delayed messages. By the way, in this particular situation that kind of reference is what I need.
Generally, soft reference is exactly like a weak reference, with subtle difference – it should stick around as long as there is plentiful memory. That reference is good, for example, for cache.
Its really week reference, used (AFAIK) only to determine when you want to know when Object is dead.
But what we can do with that knowledge about strength of references? Well, AFAIK there is two ways to solve my problem and write good code.
- Write class which “wrap” Handler class, http://stackoverflow.com/a/11408340
- Use WeakHashMap, with constant equal key like String or Integers.
I use first solution:
Write class ExtendWeakRefHandler.java, then later in usage class private method
private final ExtendWeakRefHandler mHandler = new ExtendWeakRefHandler((NameOfYourClass)this);
And in usage class I have public void function handleMessage(Message message).
..and that’s all : )
Problem solved, looking forward to next. Nah, i don’t have to look deeply in source to find another one.