Memory leak with GoogleApiClient detected by Android Studio
Asked Answered
M

1

10

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();
}

}

Moskowitz answered 10/2, 2016 at 6:22 Comment(2)
Maybe you should dig into the GoogleApiClient.Builder code,cuz it reference your Activity. I cannot find any other code you post that can cause a leak.Backbencher
OnStop could be not called by os you should use onPause onResumePrepossess
G
20

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();
Gittens answered 23/3, 2016 at 22:48 Comment(3)
Great solution! Is there a bug report in the GoogleApiClient bug tracker?Han
It's amazing that they have this bug, thanks for the solution.Streaming
hello , if i am in Fragment? getActivity().getApplicationContext() is ok?Schauer

© 2022 - 2024 — McMap. All rights reserved.