在我的各种文件中重新使用异步任务代码

时间:2013-12-12 05:21:40

标签: android service android-asynctask background-process

我想为异步任务操作创建一个类文件,并且从创建该类文件的对象开始,我希望访问这些异步任务的方法,而不使用具有不同参数的不同类文件。

异步任务的方法包括: -

OnPreExecute() - 想要为每个班级启动进度对话框。

doInbackground() - 想要执行后台操作(比如从服务器获取数据)意味着为每个类传递不同的参数。

onPostExecute() - 删除进度对话框并更新每个类的UI不同。

现在,我正在将每个类中的异步任务编写为内部类,如下所示: -

class loaddata extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AddNewLineitem.this);
            pDialog.setMessage("Loading Data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {

                }
            });
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            try {

                List<NameValuePair> params1 = new ArrayList<NameValuePair>();

                JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
                        "GET", params1);

                compoment = json.getJSONArray(COMPONENT_CODE);

                for (int i = 1; i < compoment.length(); i++) {
                    JSONObject c = compoment.getJSONObject(i);

                    String code = c.getString(CODE);
                    list_compoment.add(code);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            loadSpinnerData();
            pDialog.dismiss();

        }
    }

JSON解析器类如下: -

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();

                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;

                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;


    }
}

在oncreate()中我调用它并且它工作正常: -

new loaddata().execute();

2 个答案:

答案 0 :(得分:1)

我们可以使用不同的参数重用Aysntask。对于这个

1.创建一个接口,以便我们可以重用,传递和接收参数

public interface BackgroundListener {

public Object[] startBackgroundWork(Object... objs);
public void endBackgroundWork(Object... objs);
public void beforeBackgroundWork();


}

2.创建一个扩展Asyntask的类

BackgroundHandler.java

import android.os.AsyncTask;

public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
BackgroundListener backgroundListener;


public void setBackgroundListener(BackgroundListener aBackgroundListener)
{
   this.backgroundListener = aBackgroundListener;
}
@Override
 protected void onPreExecute() {
  backgroundListener.beforeBackgroundWork();
}
@Override
protected Object[] doInBackground(Object... objs) {



    return backgroundListener.startBackgroundWork(objs);

}

@Override
protected void onPostExecute(Object result[]) {
    backgroundListener.endBackgroundWork(result);
}

}

在活动中使用

A.java

Class A extends Activity implements BackgroundListener
{

   ...onCreate()
   {

          BackgroundHandler backgroundHandler =  new BackgroundHandler()         
          backgroundHandler.setBackgroundListner(this);
          backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type 
          // show loading bar
   } 
   public void beforeBackgroundWork()
  {
       pDialog = new ProgressDialog(A.this);
        pDialog.setMessage("Loading Data. Please wait...");
        pDialog.setIndeterminate(false);
        .....
  }
   public Object[] startBackgroundWork(Object... objs)
   {
       // access and type convert the passed parameters like objs[0], objs[1]
      //.... some time consuming stuff
      //.... some time consuming stuff
           String url_foralldropdowns = objs[0].toString();
            List<NameValuePair> params1 = new ArrayList<NameValuePair>();

            JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
                    "GET", params1);

            JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
            //Create new list_compoment here instead of global declaration
            for (int i = 1; i < compoment.length(); i++) {
                JSONObject c = compoment.getJSONObject(i);

                String code = c.getString(CODE);
                list_compoment.add(code);

            }



     retrun new Object[]{list_compoment};
   }
   public void endBackgroundWork(Object ...obj)
   {
        pDialog.dismiss();// hide loading bar
       //access resultant parameters like  objs[0], objs[1]
      //user list_component will be in obj[0]

   }
}

同样,我们可以在B.java中重用

Class B extends Activity implements BackgroundListener
{

  ...
 ....
    public void beforeBackgroundWork()
  {
       pDialog = new ProgressDialog(B.this);
        pDialog.setMessage("Loading Data. Please wait...");
        pDialog.setIndeterminate(false);
        .....
  }
   public Object[] startBackgroundWork(Object... objs)
   {

   // access and type convert the passed parameters like objs[0], objs[1]
      //.... some time consuming stuff
      //.... some time consuming stuff
           String url2 = objs[0].toString();
            List<NameValuePair> params1 = new ArrayList<NameValuePair>();

            JSONObject json = jparser.makeHttpRequest(url2,
                    "GET", params1);

            JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
             //Create new list_compoment here instead of global declaration
            for (int i = 1; i < compoment.length(); i++) {
                JSONObject c = compoment.getJSONObject(i);

                String code = c.getString(CODE);
                list_compoment.add(code);

            }



     retrun new Object[]{list_compoment};

   }
   public void endBackgroundWork(Object ...obj)
   {
      pDialog.dismiss();
       .....
          //user list_component will be in obj[0]
   }
}

答案 1 :(得分:0)

Asyntask就像其他人一样。除了AsyncTask的主要inhertited方法,您可以创建自己的方法,构造函数等。所以只需在单独的文件中创建一个单独的类。将上下文作为构造函数的参数传递。您也可以传递其他值来定义任务。

class Loaddata extends AsyncTask<String, String, String> {
    public Loaddata( pass the params){
        ... set the params
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog.setMessage("Loading Data. Please wait...");
        pDialog.show();

    }

    protected void onPostExecute() {

        // pDialog.dismiss();

    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        return null;
    }
}