Search code examples
androidandroid-studiomemory-leaksgoogle-play-servicesandroid-app-indexing

Memory leak with GoogleApiClient detected by Android Studio


I have created a new project with one class and with the following code taken from this example: https://developers.google.com/app-indexing/android/publish#add-app-indexing-api-calls

When i rotate the device several times and then click on Dump Java Heap in Android Studio and then click on Analyse. I will get a result showing that my MainActivity has leaked.

The reason why I have created this example project, is because I have an existing app that has a Memory Leak problem (StrictMode and Android Studio says so), and my conclusion is that it is my AppIndex code that are causing the problem.

Is it a bug in Android Studio or is it a real memory leak?

public class MainActivity extends AppCompatActivity {


private GoogleApiClient mClient;
private Uri mUrl;
private String mTitle;
private String mDescription;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    mUrl = Uri.parse("http://examplepetstore.com/dogs/standard-poodle");
    mTitle = "Standard Poodle";
    mDescription = "The Standard Poodle stands at least 18 inches at the withers";
}


public Action getAction() {
    Thing object = new Thing.Builder()
            .setName(mTitle)
            .setDescription(mDescription)
            .setUrl(mUrl)
            .build();

    return new Action.Builder(Action.TYPE_VIEW)
            .setObject(object)
            .setActionStatus(Action.STATUS_TYPE_COMPLETED)
            .build();
}

@Override
public void onStart() {
    super.onStart();
    mClient.connect();
    AppIndex.AppIndexApi.start(mClient, getAction());
}

@Override
public void onStop() {
    AppIndex.AppIndexApi.end(mClient, getAction());
    mClient.disconnect();
    super.onStop();
}

}


Solution

  • It seems GoogleApiClient.Builder(this) is causing the leak, because current activity is being kept by API client. mClient.disconnect() is not going to release it. I have solved it for myself by replacing "this" with getApplicationContext(). The application context lives as long as the process lives.

    mClient = new GoogleApiClient.Builder(getApplicationContext()).addApi(AppIndex.API).build();