我正在看这个例子 https://developer.android.com/training/location/retrieve-current.html#CheckServices
以下是相关代码:
public class MainActivity extends FragmentActivity {
...
private boolean servicesConnected() {
...
if (ConnectionResult.SUCCESS == resultCode) {
...
// Google Play services was not available for some reason.
// resultCode holds the error code.
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
...
}
}
}
如果我们查看GooglePlayServicesUtil.getErrorDialog(..)
,我们会将this
的引用传递给Activity
。
问题是: 在配置更改期间是否会导致内存泄漏?
我想答案取决于GooglePlayServicesUtil.getErrorDialog(..)
如何/内部保留对Activity
的引用。
答案 0 :(得分:1)
是的,我的应用程序曾经泄漏
如果您有谷歌播放服务错误对话框,然后再次旋转它将泄漏
这是我为解决泄漏而采取的解决方案,但这假设您的Google Play服务检查位于onResume
public class MainActivity extends Activity
{
private Dialog googlePlayErrorDialog;
@Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();
int isAvaiable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(isAvaiable == ConnectionResult.SUCCESS)
{
Log.d("TEST", "GPS IS OK");
}
else if(isAvaiable == ConnectionResult.SERVICE_MISSING ||
isAvaiable == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED ||
isAvaiable == ConnectionResult.SERVICE_DISABLED)
{
googlePlayErrorDialog = GooglePlayServicesUtil.getErrorDialog(isAvaiable, this, 10);
googlePlayErrorDialog.show();
}
}
@Override
protected void onPause()
{
// TODO Auto-generated method stub
super.onPause();
if(googlePlayErrorDialog != null)
{
googlePlayErrorDialog.dismiss();
}
}
所以这里的交易是我将getErrorDialog设置为一个我自己的对话框变量,然后在onPause中做一个简单的空检查(以避免可怕的空指针异常!)并调用dismiss。
如果您想了解更多信息,我从阅读本书中得到了这个想法
http://publicstaticdroidmain.com/2012/01/avoiding-android-memory-leaks-part-1/