gpt4 book ai didi

android - 通用AsyncTask,在多个上下文中使用一个AsyncTask

转载 作者:行者123 更新时间:2023-11-29 14:32:34 25 4
gpt4 key购买 nike

我正在使用 AsyncTask,我发现的关于 AsyncTask 的所有示例都在一个 Activity 中。

我正在尝试制作一个有很多 Activity 的应用程序,有些应用程序必须下载 HTML 页面。我真的不想在每个 Activity 中一直复制粘贴相同的代码。我觉得这很脏。

所以我需要将它作为一个特殊的类 Async HttpGet 来完成,并传递带有参数的函数。我将在 doinbackground 之后执行(每个 Activity 都不同)。

这是可能的还是我需要在每个 Activity 中复制粘贴我的代码并更改后台执行以在下载 HTML 页面后执行我需要的操作?

最佳答案

这是一个 AsyncTask,它将从 url 下载数据并更新调用 Activity 。

确保您的调用 Activity 实现接口(interface) DownloadDataTask.DownloadCompleteHandler 并将其自身作为参数传递给 DownloadDataTask 构造函数。

public class DownloadDataTask extends AsyncTask<String, Integer, String> {

public interface DownloadCompleteHandler
{
public void handleDownloadComplete(String result);
}

private DownloadCompleteHandler handler;
private String url;

public DownloadDataTask(DownloadCompleteHandler handler, String url) {
this.handler = handler;
this.url = url;
}


/* AsyncTask methods */

@Override
protected String[] doInBackground(String... empty) {
return downloadData(url);
}

@Override
protected void onPostExecute(String result) {
handler.handleDownloadComplete(result);
}

/* Downloading Data */

private String downloadData(String urlStr) {
InputStream is = null;
String result = new String();

try {
is = getInputStream(urlStr);

BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
} catch (MalformedURLException ex) {
return "Malformed URL: " + ex.getMessage();
} catch (SocketTimeoutException ex) {
return "Connection timed out";
} catch (IOException ex) {
return "IOException: " + ex.getMessage();
}

finally {
if (is != null)
is.close();
}

return result;
}

private InputStream getInputStream(String urlStr) throws IOException
{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("GET");
conn.setDoInput(true);

conn.connect();
return conn.getInputStream();
}
}

关于android - 通用AsyncTask,在多个上下文中使用一个AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16478099/

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