我正在使用带有保留片段的简单活动,其中包含活动使用的一些数据。保留的片段使用加载器从内容提供者获取数据。在配置更改(屏幕旋转)时,活动被重新创建并且旧实例被泄漏,正如 LeakCanary 库报告的那样(保留片段 -> 加载器管理器 -> 旧活动)。这与 support-v4 23.0.0 库(以及以前的版本)一起复制。带有保留片段的活动示例,其中复制了泄漏(此处没有有用的代码,仅用于演示泄漏):
package com.leaksample;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private ModelFragment mModelFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
mModelFragment = (ModelFragment) fm.findFragmentByTag(ModelFragment.TAG);
if (mModelFragment == null) {
mModelFragment = new ModelFragment();
fm.beginTransaction()
.add(mModelFragment, ModelFragment.TAG)
.commit();
fm.executePendingTransactions();
}
}
public static class ModelFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = ModelFragment.class.getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media.DATA}, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
}
来自 LeakCanary 的堆栈:
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ In com.leaksample:1.0:1.
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ * com.leaksample.MainActivity has leaked:
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ * GC ROOT thread java.lang.Thread.<Java Local> (named 'Binder_1')
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ * references android.view.ViewRootImpl.mContext
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ * references com.leaksample.MainActivity.mModelFragment
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ * references com.leaksample.MainActivity$ModelFragment.mLoaderManager
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ * references android.support.v4.app.LoaderManagerImpl.mHost
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ * references android.support.v4.app.FragmentActivity$HostCallbacks.this$0
08-29 19:52:34.129 15271-16632/com.leaksample D/LeakCanary﹕ * leaks com.leaksample.MainActivity instance
也许我做错了什么,忘记调用一些close
或release
方法?我认为将保留的片段与加载器一起使用是一种常见的模式,这里不应该是内存泄漏。