我正在使用 AsyncTask,我发现的关于 AsyncTask 的所有示例都在一个活动中。
我正在尝试制作一个有很多活动的应用程序,有些必须下载一个 HTML 页面。我真的不想在每个活动中一直复制粘贴相同的代码。我觉得这很脏。
所以我需要将它作为一个特殊的类 Async HttpGet 并用参数传递函数。我将在 doinbackground 之后执行(每个活动都不同)。
这是可能的还是我需要在每个活动中复制粘贴我的代码并在后台更改执行以在下载 HTML 页面后执行我需要的操作?
我正在使用 AsyncTask,我发现的关于 AsyncTask 的所有示例都在一个活动中。
我正在尝试制作一个有很多活动的应用程序,有些必须下载一个 HTML 页面。我真的不想在每个活动中一直复制粘贴相同的代码。我觉得这很脏。
所以我需要将它作为一个特殊的类 Async HttpGet 并用参数传递函数。我将在 doinbackground 之后执行(每个活动都不同)。
这是可能的还是我需要在每个活动中复制粘贴我的代码并在后台更改执行以在下载 HTML 页面后执行我需要的操作?
只需创建一个AsyncTask
可以重用的扩展类。
public abstract class MyAsyncTask extends AsyncTask<Void, Void, String> {
private final String url;
public MyAsyncTask(String url){
this.url = url;
}
@Override
protected String doInBackground(Void... params){
// get data from url.
return null;
}
}
然后调用它,只需创建该类的一个实例。
new MyAsyncTask("http://www.google.com"){
public void onPostExecute(String result){
// update your views.
}
}.execute();
这是一个 AsyncTask,它将从 url 下载数据并更新调用活动。
确保您的调用活动实现了该接口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();
}
}
那么您可以做的是为 AsyncTask 完成创建一个侦听器,该侦听器在您的 AsyncTask 完成时进行侦听并返回数据。我创建了一个示例来在后台线程中执行数据库查询,然后将数据返回给 Activity。只是check it
,您可以为您的问题创建类似的 AsyncTask。
更新:-