Google PlusOneButton leaks a context

177 Views Asked by At

I've started tracking memory leaks on my Android app and, thanks to the great LeakCanary library, I found that some of my activities that include a GooglePlusButton are leaking a context.

Unfortunately I didn't find a workaround to avoid it. As described on this old bug report, the initialize method hides the fact that its needs a context. Furthermore, it needs an Activity context; the Android studio decompiler shows it (the bug reporter tell it as well):

public void initialize(String var1, int var2) {
   zzab.zza(this.getContext() instanceof Activity, "To use this method, the PlusOneButton must be placed in an Activity. Use initialize(String, OnPlusOneClickListener).");

Is there any workaround better than completely get rid of the +1 button?

Note: I'm using Google Play Services 9.6.0 but this problem also occurred on previous versions.

2

There are 2 best solutions below

1
Alexander77 On

As it is said in the error message if you are using G+1 button not in an activity (for example in the app bar menu) you need to initialise it by calling method initialize(String, OnPlusOneClickListener).

Updates the +1 button with a URL. Most apps call this method each time the button is in focus (for example, in the Activity onResume method). To use this method, the PlusOneButton must be placed in an Activity. Use initialize(String, OnPlusOneClickListener) otherwise.

More info here: https://developers.google.com/android/reference/com/google/android/gms/plus/PlusOneButton

0
Jérémy Reynaud On

The previous answer points me in a new direction. I finally manage it by creating the G+1 button dynamically and giving the constructor the Application context:

mPlusOneButton =  new PlusOneButton(getApplicationContext());
parent.addView(mPlusOneButton);
...
mPlusOneButton.initialize(..., new PlusOneButton.OnPlusOneClickListener() {
        @Override
        public void onPlusOneClick(Intent intent) {...}
      });