gpt4 book ai didi

java - 为什么这不会通知线程?

转载 作者:行者123 更新时间:2023-11-29 09:12:54 24 4
gpt4 key购买 nike

我一直想知道大多数应用程序是如何创建确认对话框的,我可以让我的应用程序正常工作。我知道你不能阻止 UI 线程,所以我有这样的东西:

private synchronized boolean createDialogConfirm() {
if(DEBUG) Log.i("Dialog", "createDialogConfirm()");
// Creo un nuevo Thread que crea el cuadro de dialogo TODO: no funciona la confirmacion, nunca llega al return
runOnUiThread(new Runnable() {
@Override
public void run() {
// Creo el dialogo con los dos botones
AlertDialog.Builder confirm = new AlertDialog.Builder(LogicAnalizerView.this);
confirm.setTitle("Guardar");
confirm.setMessage("El archivo existe, sobreescribir ?");
if(DEBUG) Log.i("Dialog", "createDialogConfirm() -> Created");

// Boton Si
confirm.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
state = true;
synchronized(this) { this.notifyAll(); }; // Despierta el Thread
}
});

// Boton No
confirm.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
state = false;
synchronized(this) { this.notifyAll(); };
dialog.dismiss();
}
});
confirm.show();
}
});

if(DEBUG) Log.i("Dialog", "createDialogConfirm() - Thread created");
try {
synchronized(this) { wait(); }; // Queda esperando (no retorna nada) hasta que se llame a notify() en algun boton
} catch (InterruptedException e) {
e.printStackTrace();
}

return state;
}

所以我在线程(不是 UI 线程)中以这种方式使用它:

if(createDialogConfirm()){ ... }

我知道这是一种丑陋的方式,但我不知道其他方式,如果你有任何人我很想听听。问题是,如果我调用 notifyAll() 或 notify() whitout synchronized(this){} 我会在我的应用程序上强制关闭,但如果我使用它,它永远不会返回,似乎永远不会 notify() 线程。这个想法是从线程返回 true 或 false,但仅当用户按下某个按钮时。

最佳答案

您可以使用 Interface 从 AlertDialog 中获取通知/返回一些值。查看我的回答here .

关于java - 为什么这不会通知线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11304648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com