gpt4 book ai didi

java - Android:使用简单的警报对话框处理 AsyncTask 中的 SocketTimeoutException

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:06 24 4
gpt4 key购买 nike

我在我的 Android 应用程序中使用 AsyncTask 从服务器获取一些数据。为了建立连接,我使用了超时为 10 秒的 HttpURLConnection 类。现在,我想在(如果)该时间到期时显示一个简单的 AlertDialog,并带有一个将用户带回 Main Activity 的 OK 按钮。现在,这就是我的应用程序 (DoorActivity) 的相关部分的样子:

    protected String doInBackground(String... params) {

try {

URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("GET");
if (urlConnection.getResponseCode() != 200) {
throw new IOException(urlConnection.getResponseMessage());
}

BufferedReader read = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
jsonString = read.readLine().toString();

} catch (MalformedURLException malformedUrlException) {
System.out.println(malformedUrlException.getMessage());
malformedUrlException.printStackTrace();

} catch (SocketTimeoutException connTimeout) {
showTimeoutAlert();

showTimeoutAlert() 方法位于 DoorActivity 的根类中,如下所示:

protected void showTimeoutAlert(){
TextView timeoutWarning = new TextView(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog alertDialog;
timeoutWarning.setText(R.string.conn_timeout_warning);
builder.setView(timeoutWarning);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(DoorActivity.this, MainActivity.class);
startActivity(intent);
}
});
alertDialog = builder.create();
alertDialog.show();
}

现在,当我运行这个应用程序时,服务器故意脱机,我得到以下异常:

java.lang.RuntimeException: 执行 doInBackground() 时发生错误

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

最佳答案

showTimeoutAlert(); 不应在 doInBackground() 中调用。任何与 UI 相关的代码都应该放在 onPostExecute() 中。

例如:

private boolean socketTimedOut = false;

@Override
protected String doInBackground(String... params) {
try {
...
} catch (SocketTimeoutException connTimeout) {
this.socketTimedOut = true;
}
}


@Override
protected void onPostExecute(String result) {
if(this.socketTimedOut){
showTimeoutAlert();
}
}

替代方案(不推荐):

@Override
protected String doInBackground(String... params) {
try {
...
} catch (SocketTimeoutException connTimeout) {
runOnUiThread(new Runnable() {
public void run() {
showTimeoutAlert();
}
});
}
}

关于java - Android:使用简单的警报对话框处理 AsyncTask 中的 SocketTimeoutException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34637815/

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