我有一个Android应用程序,当值是“ 1”时会显示一个对话框,并反复显示该对话框,直到该值设置为“ 0”为止。 Runnable
调用Handler
会启动对话框,并且Runnable
会延迟循环。
问题是,当我转到具有相同功能的其他活动并返回时,该对话框已经打开。这导致我的应用崩溃。我已经尝试使用removeMessage和removeCallback,但是仍然有问题。Handler
Handler myHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
/* Dialog */
final AlertDialog.Builder AlertAlarm_Build;
LayoutInflater inflater = (LayoutInflater) Settings_Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertAlarm_Build = new AlertDialog.Builder(Settings_Activity.this);
final View Disengaged_View;
Disengaged_View = inflater.inflate(R.layout.disengage_dialog,null);
final AlertDialog PasswordDialog = AlertAlarm_Build.create();
PasswordDialog.show();
final String[] given_password = new String[1];
final boolean[] Password_Pass = {false};
//respose
final RequestQueue requestHander;
requestHander = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
...//Ask for password
//New
PasswordDialog.setOnDismissListener(new DialogInterface.OnDismissListener()
{
@Override
public void onDismiss(DialogInterface dialogInterface)
{
recreate();
}
});
}
};
Runnable
//Runnable
final Runnable aMyRunnable = new Runnable()
{
@Override
public void run()
{
RequestQueue requestRun;
requestRun = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
if(New_engaged[0].equals("1") && New_alarm[0].equals("1"))
{
set_engaged[0] = "1";
myHandler.sendEmptyMessage(0);
}
else
{
requestRun.add(JOR_SystemCheck);
myHandler.postDelayed(this,5000);
}
}
};
onStop
protected void onStop() {
super.onStop();
myHandler.removeCallbacksAndMessages(aMyRunnable);
myHandler.removeMessages(0);
}
错误
/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.djwiz.eclipse5, PID: 17705
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@f8866f3 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:765)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
at android.app.Dialog.show(Dialog.java:330)
at com.example.djwiz.eclipse5.Settings_Activity$1.handleMessage(Settings_Activity.java:68)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
最佳答案
基于removeCallbacksAndMessages
的文档
删除obj为令牌的回调和已发送消息的所有未决帖子。如果token为null,则将删除所有回调和消息
您的代码与任何令牌都不匹配:myHandler.removeCallbacksAndMessages(aMyRunnable);
因此解决方案是使用:myHandler.removeCallbacksAndMessages(null);