我在Activity example.activity.SetupManage中。在一些操作之后,我调用一个显示通知消息的对话框。但即使我没有单击“确定”按钮,也会执行所有后续代码,因此当我杀死所有“活动”时,对话框会产生问题。我能做些什么来解决我的问题?
AlertDialog myAlertDialog;
public void onDestroy(Bundle savedInstanceState){
if(myAlertDialog.isShowing())
myAlertDialog.dismiss();
}
// *** some operations *** //
try{
myAlertDialog = new AlertDialog.Builder(this)
.setTitle("Notification")
.setMessage("Operation Failed")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
catch(Exception ex){
}
try{
Intent myIntent = new Intent();
myIntent.setClassName("example.activity", "example.activity.MainActivity");
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(myIntent);
}catch(Exception ex){
}
错误讯息:
10-16 15:33:11.120: E/WindowManager(4360): Activity example.activity.SetupManage has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@415ca638 that was originally added here
10-16 15:33:11.120: E/WindowManager(4360): at example.activity.SetupManage.CleanDatabase(SetupManage.java:61)
10-16 15:33:11.120: E/WindowManager(4360): at android.view.ViewRoot.<init>(ViewRoot.java:288)
10-16 15:33:11.120: E/WindowManager(4360): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:249)
10-16 15:33:11.120: E/WindowManager(4360): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:193)
10-16 15:33:11.120: E/WindowManager(4360): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:118)
10-16 15:33:11.120: E/WindowManager(4360): at android.view.Window$LocalWindowManager.addView(Window.java:532)
10-16 15:33:11.120: E/WindowManager(4360): at android.app.Dialog.show(Dialog.java:269)
10-16 15:33:11.120: E/WindowManager(4360): at android.app.AlertDialog$Builder.show(AlertDialog.java:907)
10-16 15:33:11.120: E/WindowManager(4360): at example.activity.SetupManage.CleanDatabase(SetupManage.java:61)
答案 0 :(得分:2)
它继续执行,因为这就是你告诉它要做的事情。如果您希望在关闭对话框时执行代码,请将其放在对话框按钮的onClick
或onDismiss
(如果可用)中。
更重要的是,为什么onDestroy()
中的任何一个首先出现?这似乎是一个非常糟糕的地方放置一个对话框(或一个意图在99.8%的时间内调用另一个活动)。你将永远无法看到它,活动正在被立即销毁。我建议重新考虑你的程序流程。
答案 1 :(得分:1)
Replace this code , it can help you...pass getApplication context
try{
myAlertDialog = new AlertDialog.Builder(getApplicationContext() )
.setTitle("Notification")
.setMessage("Operation Failed")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
catch(Exception ex){
}
答案 2 :(得分:0)
将AlertDialog保存到变量:
myAlertDialog = new AlertDialog.Builder(this).....
并且在onPause()方法中,如果对话框处于活动状态,则应将其关闭!