我对stackoverflow还是相当陌生,已经尽我所能解释了一切,感谢您的帮助,在以下方面确实很费劲。
我正在执行大量计算(数据下载),如下所示:
public static String fetchhttp_2(String urlstring) {
String value = null;
try {
HttpPost httpPost = new HttpPost(urlstring);
BasicHeader d = new BasicHeader("X-Zomato-API-Key", CommonLib.APIKEY);
httpPost.addHeader(d);
BasicHeader d2 = new BasicHeader("Authorization", "Basic emRldjoxTjRDMlFBOVUyNUNrcDE=");
httpPost.addHeader(d2);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("access_token", prefs.getString("access_token", "")));
nameValuePairs.add(new BasicNameValuePair("client_id", CommonLib.CLIENT_ID));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = HttpManager.execute(httpPost);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
value = convertStreamToString(in).toString();
return value;
} else {
CommonLib.ZLog("responsecode", urlstring + " --- " + responseCode);
}
} catch (Exception e) {
CommonLib.ZLog("Error fetching http url", e.toString());
e.printStackTrace();
}
return value;
}
在大多数情况下(除了响应给我大量数据的情况下),这都是可行的。
我尝试了以下方法:
从异步任务中调用它。
private class MyClass extends AsyncTask<Void, Void, Boolean> {
ArrayList<myList> restaurants = null;
@Override
protected Boolean doInBackground(Void... p) {
String url = "http://myUrl.com";
myObj = // get data from url using snippet above
}
在我的oncreate中:
new GetRestaurantCompact().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
在线程中启动它:
Runnable r = new Runnable() {
public void run() {
// same code the goes in async task
}
Thread th = new Thread(r);
th.start();
在服务中启动此代码
Intent i= new Intent(context, MyService.class);
context.startService(i);
辅助功能
`
public static String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (Exception e) {
return "";
} catch (OutOfMemoryError ex) {
CommonLib.ZLog("splash", "Out of memory exception while download");
return "";
}
}`
我尝试将服务代码以及异步线程放入Async中。
问题是,该任务占用了UI线程,并使UI无响应,直到结束为止。
没有人真的有帮助
最佳答案
尝试设置线程的优先级:
Thread th = new Thread(runnable);
th.setPriority(Thread.MIN_PRIORITY);
th.start();