【发布时间】:2014-06-20 12:54:24
【问题描述】:
为了让我的活动发挥作用,我必须从互联网上获取数据。
我实现了线程,但我对 Java 或线程还不是很擅长,所以我有点匆忙通过它只是希望它能工作。它工作得很好,但 UI 有时感觉很慢,因为它需要一段时间才能显示活动。
这是我的代码
一个活动,我们称之为 MainActivity 调用:
JSONObject Data = WebApi.getData(id);
WebApi 类将 url 拼凑在一起:
public static JSONObject getData(String id) {
String url = URL;
url += DATA_URL;
url += VALUE_DATA_ID + id;
return WebInterface.executeWeb(url);
}
并将其交给 WebInterface,在 WebInterface 中整个事情被执行:
public static String getUrl(final String url) {
final StringBuilder sb = new StringBuilder();
Thread thread = new Thread(new Runnable() {
public void run()
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String result, line = reader.readLine();
result = line;
while((line=reader.readLine())!=null){
result+=line;
}
sb.append(result);
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = sb.toString();
Log.d(App.TAG, result);
return result;
}
public static JSONObject executeWeb(final String url) {
String result = WebInterface.getUrl(url);
JSONObject json = null;
try {
json = new JSONObject(result.trim());
} catch (JSONException e) {
try {
json = new JSONObject("{}");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return json;
}
这很好用,但我觉得如果我用 ASyncTask 实现它会更好。我的活动可能会显示一些缓存数据,直到出现“真实”数据。 AsyncTask 可以吗?我需要为此重做很多代码吗?
提前感谢您的帮助!
编辑:
感谢建议 AsyncTaskLoader 的人(我认为有人删除了他的答案) 我是用 AsyncTaskLoader 做的,非常好用,非常简单!
【问题讨论】:
-
我不知道你为什么认为你需要改变它。如果您要使用
AsyncTask显示一些缓存数据,那么为什么不能没有? -
@codeMagic 他建议显示缓存数据,然后显示新获取的数据,但他当前的实现不加载缓存数据。我建议检查 Loader 和 LoaderManager 以在后台加载您需要的东西。它为你做 AsyncTask 的事情。
-
我会自己实现缓存机制。我只是不知道如何执行异步任务
标签: java android multithreading android-asynctask