我有一个活动,如果是第一次开始,它会显示欢迎信息:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showWelcomeMessageIfNecessary();
}
private void showWelcomeMessageIfNecessary() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Editor edit = prefs.edit();
if (!prefs.getBoolean("welcomemessage", false)) {
edit.putBoolean("welcomemessage", true);
edit.commit();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.messages_welcome_content).setCancelable(false).setPositiveButton(R.string.errors_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do nothing
}
}).setTitle(R.string.messages_welcome_title);
AlertDialog alert = builder.create();
alert.show();
}
}
这一切都很好,但是当我启动应用程序,并立即旋转屏幕,我得到了众所周知的窗口泄漏异常。
我该怎么阻止呢?有没有更好的方法来显示对话框?当我使用
ProgressDialog
s inAsyncTask
s inFragment
s时,也会发生这种情况。 最佳答案
您需要取消活动的onstop或ondestroy方法中的对话框。例如:
private AlertDialog diag = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
diag = showWelcomeMessageIfNecessary();
if(diag != null)
diag.show();
}
private AlertDialog showWelcomeMessageIfNecessary() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Editor edit = prefs.edit();
AlertDialog alert = null;
if (!prefs.getBoolean("welcomemessage", false)) {
edit.putBoolean("welcomemessage", true);
edit.commit();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.messages_welcome_content).setCancelable(false).setPositiveButton(R.string.errors_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do nothing
}
}).setTitle(R.string.messages_welcome_title);
alert = builder.create();
}
return alert;
}
@Override
protected void onStop() {
super.onStop();
if(diag != null)
diag.dismiss();
}