Reputation: 57
I am trying the control of admob in libgdx. I found some java codes but I could not translate java to kotlin. Can you help me. Thanks.
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected AdView adView;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case SHOW_ADS:
adView.setVisibility(View.VISIBLE);
break;
case HIDE_ADS:
adView.setVisibility(View.GONE);
break;
}
}
};
Android studio converted like this
var handler: Handler = object : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
SHOW_ADS -> adView.setVisibility(View.VISIBLE)
HIDE_ADS -> adView.setVisibility(View.GONE)
}
}
}
the error:This Handler class should be static or leaks might occur (anonymous android.os.Handler)
Upvotes: 0
Views: 875
Reputation: 93629
This implementation is overly complicated in the first place. Just use a standard Handler without subclassing it and modifying how it handles messages. You can post a Runnable to it instead. Then you don't have to worry about message codes either.
private val handler = Handler(Looper.getMainLooper())
override fun showAds(show: Boolean) = handler.post {
adView.visibility = if (show) View.VISIBLE else View.GONE
}
Upvotes: 2
Reputation: 57
I found a good solution.
private val handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
when(msg.what){
SHOW_ADS->{adView.setVisibility(View.VISIBLE)}
HIDE_ADS->{adView.setVisibility(View.GONE)}
}
Upvotes: 0
Reputation: 2335
By overriding Handler
's public void handleMessage(Message msg)
you have created an anonymous
class. In short there is a good possibility that the handler could exist longer than the enclosing class. Which is a no no because an inner class is referenced by the outer class. Easiest fix is to make a separate class
that extends
Handler
and override handleMessage(Message msg)
there instead of inside of the other class.
EDIT when it comes to any Android OS specific classes Fragments/Activities...
anonymous
classes don't work, for same reason why you don't pass args
into constructors of fragments
.
Upvotes: 1