【发布时间】:2013-05-14 10:11:06
【问题描述】:
我正在尝试在我的应用中实现超时行为。在超时实际发生前 5 秒还应该有一个警告(alertdialog)。
我想使用 ScheduledExecutorService 来执行此操作。
到目前为止,这是我的相关代码:
private final Context context = this;
private ScheduledExecutorService sExService = Executors.newScheduledThreadPool(2);
private RunnableScheduledFuture<?> sFutureTimeout;
private RunnableScheduledFuture<?> sFutureDisconnect;
private final Runnable timeoutRunnable = new Runnable(){
@Override
public void run() {
showTimeoutAlertDialog();
}
};
private final Runnable disconnectRunnable = new Runnable(){
@Override
public void run() {
disconnect();
}
};
以及处理超时行为的方法:
private void setTimeout(){
sFutureTimeout = (RunnableScheduledFuture<?>) sExService.schedule(timeoutRunnable, 5, TimeUnit.SECONDS);
}
setTimeout 在 onCreate() 中被调用,所以应用应该在启动后 5s 断开连接。
private void showTimeoutAlertDialog(){
new AlertDialog.Builder(context)
.setTitle("Disconnect in 5s")
.setCancelable(false)
.setPositiveButton("Abort",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
sFutureDisconnect.cancel(false);
setTimeout();
}
}).show();
sFutureDisconnect = (RunnableScheduledFuture<?>) sExService.schedule(disconnectRunnable, 5, TimeUnit.SECONDS);
}
这是我面临的问题:
如果“setTimeout”中调用的runnable设置为“disconnectRunnable”,则运行正常,应用在5s后断开连接。
当我将其设置为 'timeoutRunnable' 时,不会显示 alertDialog + 应用程序永远不会断开连接,即使在“showTimeoutAlertDialog”中 5 秒后应该调用 'disconnectRunnable'!?
我认为这里的 ScheduledExecutorService 出了点问题,但我找不到解决方案。
感谢您的帮助:)
【问题讨论】:
标签: java android timeout android-alertdialog scheduledexecutorservice