Android Studio检测到GoogleApiClient导致内存泄漏

时间:2016-02-10 06:22:47

标签: android android-studio memory-leaks google-play-services android-app-indexing

我创建了一个包含一个类的新项目,并从此示例中获取了以下代码: https://developers.google.com/app-indexing/android/publish#add-app-indexing-api-calls

当我多次旋转设备然后在Android Studio中单击Dump Java Heap然后单击Analyze。我会得到一个显示我的MainActivity已泄露的结果。

我创建这个示例项目的原因是因为我有一个存在内存泄漏问题的现有应用程序(StrictMode和Android Studio这样说),我的结论是我的AppIndex代码导致问题

它是Android Studio中的错误还是真正的内存泄漏?

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

}

1 个答案:

答案 0 :(得分:20)

似乎GoogleApiClient.Builder(this)导致泄漏,因为当前活动由API客户端保留。 mClient.disconnect()不会发布它。我用getApplicationContext()替换了“this”,为自己解决了这个问题。只要流程存在,应用程序上下文就会存在。

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