Android中后台任务中的大量计算

时间:2014-03-11 05:48:28

标签: java android multithreading performance

我对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无响应,直到它结束。

没有人帮助

1 个答案:

答案 0 :(得分:0)

尝试设置线程的优先级:

Thread th = new Thread(runnable);
th.setPriority(Thread.MIN_PRIORITY);
th.start();