如何在服务中嵌入AsyncTask

时间:2015-04-12 11:39:02

标签: android service android-asynctask

我正在尝试调用此类,它在服务

中扩展AsyncTask
class LoadAllProducts extends AsyncTask<String, String, String>{
    /**
     * getting All products from url
     */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    id = c.getString(TAG_PID);
                    name = c.getString(TAG_NAME);
                    latb = c.getString(TAG_LATITUDE);
                    lngb = c.getString(TAG_LONGITUDE);

                    Double lal = Double.parseDouble(latb);
                    Double lol = Double.parseDouble(lngb);

                    double dist = docar(lal, lol);

                    if (dist < 2000) {
                        Intent dfsjk = new Intent(GetFindService.this, MainActivity.class);
                        startActivity(dfsjk);
                    }
                }
            } else {
                // no products found
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

}

我将其称为如下

new LoadAllProducts().execute();

我应该单独声明该课程,还是如何在不崩溃应用程序的情况下成功调用它?

1 个答案:

答案 0 :(得分:0)

你有什么尝试?没有什么可以阻止您在AsyncTask内使用Service。但是,如果您只需要在一个线程(主要线程除外)上执行一项任务,请考虑使用IntentService。来自docs

  

IntentService是处理异步的Services的基类   请求(表示为Intents)。客户端发送请求   通过startService(Intent)调用;该服务根据需要启动,   使用工作线程依次处理每个Intent,并自行停止   当它用完了。