gpt4 book ai didi

android - 在非 Activity 类的 AsyncTask 中 toast

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:31:28 25 4
gpt4 key购买 nike

我有一个非 Activity 类,它包含一个调用 URL 的 AsyncTask。如果由于某些原因连接超时,我想通过张贴 toast 让用户知道这一点。但我无法获得任何上下文。

如何实现这一点?

RPIcall.class

import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.IOException;

class RPicall extends AsyncTask<String, String, Void> {

@Override
protected Void doInBackground(String... uri) {

int timeoutSocket = 3000;
int timeoutConnection = 3000;

try{

Log.v("call URL: ", uri[0]);

HttpGet httpGet = new HttpGet(uri[0]);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.

HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.

HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

} catch (ClientProtocolException e) {
//Here Connection TimeOut excepion
//Toast.makeText(, "Your connection timedout", Toast.LENGTH_SHORT).show();
Log.v("Server not Reachable: ", uri[0]);
publishProgress("TimeOut");

} catch (HttpHostConnectException e) {

Log.e("Server not Reachable: ", uri[0]);

}

catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String test = "test";
Log.v("finished: ", test);

}
}

最佳答案

第 1 步:向 RPicall 添加一个构造函数,它接受一个 Context,并将其存储在一个数据成员中。

第 2 步:在 onPostExecute() 中使用 Context 来显示您的 Toast

第 3 步:在创建 RPicall 实例时传递合适的 Context

关于android - 在非 Activity 类的 AsyncTask 中 toast ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28659165/

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