java - 我想在 android 应用程序中实现 AsyncTask 并行执行器

标签 java android multithreading android-asynctask concurrent-programming

我已经实现了串行 AsnycTask 但我想并行转换它,请帮助我。我的代码如下所示。

 public class ExpressNews extends Activity {

    // All static variables
    String URL = "http://www.express.pk/feed/";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "title";
    static final String KEY_NAME = "title";
    static final String KEY_COST = "title";
    static final String KEY_DESC = "description";

    int disable = 0;

    ArrayList<HashMap<String, String>> menuItems;
    XMLParser parser;

    CopyOfXMLParser parser1;
    String xml;
    Document doc;
    NodeList nl, n2;

    HashMap<String, String> map1;
    Element e, title;
    CharacterData titleCDATA;
    String abc;
    String[] testarray, testarray1, testarray2, testarray3, finalarray;
    String[] c, c1;
    InputSource is;
    TextView txt1;
    String attributes;

    int li, si;
    int ai = 0;
    int s = 22;
    int click = 0;
    int par = 0;
    Customlistadapter adapter;
    PullToRefreshListView lv;

    String shref = "";

    ProgressDialog PD;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt1 = (TextView) findViewById(R.id.name);
        lv = (PullToRefreshListView) findViewById(R.id.listView);
        new MyAsync().execute();

    }

    private class MyAsync extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            PD = new ProgressDialog(ExpressNews.this);
            PD.setTitle("Please Wait..");
            PD.setMessage("Loading...");
            PD.setCancelable(false);
            PD.show();
        }

        @Override
        protected void onPostExecute(Void result) {
            PD.dismiss();

            si = menuItems.size();

            testarray = new String[si];
            testarray1 = new String[si];
            for (HashMap<String, String> map : menuItems) {

                String value = map.get(KEY_NAME);
                String value1 = map.get(KEY_DESC);

                testarray[ai] = value;
                testarray1[ai] = value1;

                ai++;

            }

            is = new InputSource();
            is.setCharacterStream(new StringReader(xml));

            listviewmethod();
            new MyAsync1().execute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            menuItems = new ArrayList<HashMap<String, String>>();

            parser = new XMLParser();

            xml = parser.getXmlFromUrl(URL); // getting XML
            doc = parser.getDomElement(xml); // getting DOM element

            nl = doc.getElementsByTagName(KEY_ITEM);

            li = nl.getLength();

            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                map1 = new HashMap<String, String>();
                e = (Element) nl.item(i);

                map1.put(KEY_ID, parser.getValue(e, KEY_ID));
                map1.put(KEY_NAME, parser.getValue(e, KEY_NAME));
                map1.put(KEY_COST, parser.getValue(e, KEY_COST));

                title = (Element) e.getElementsByTagName("content:encoded")
                        .item(0);

                NodeList mediacontentList = e
                        .getElementsByTagName("media:content");
                Element mediacontentElement = (Element) mediacontentList
                        .item(0);

                attributes = mediacontentElement.getAttribute("url");

                titleCDATA = (CharacterData) title.getChildNodes().item(0);

                abc = (titleCDATA.getData());

                abc = abc.replace("<p>", "");
                abc = abc.replace("<b>", "");
                abc = abc.replace("&nbsp;", "");
                abc = abc.replace("</strong>", "");

                abc = abc.replace("<strong class='location'>", "");

                abc = abc.replace("<p align=", "");

                abc = abc.replace("right", "");

                abc = abc.replace(":&nbsp;", "");
                abc = abc.replace("</p>", "");

                abc = abc.replace("a", "");

                abc = abc.replace("b", "");

                abc = abc.replace("c", "");

                abc = abc.replace("d", "");

                abc = abc.replace("<", "");
                abc = abc.replace(">", "");
                abc = abc.replaceAll("\"", "");

                abc = abc.replace("_", "");
                abc = abc.replace("/", "");
                abc = abc.replace("+", "");
                abc = abc.replace("-", "");
                abc = abc.replace("$", "");
                abc = abc.replace("&", "");
                abc = abc.replaceAll("\\<.*?\\> ?", "");

                abc = abc.replaceAll("\\;.*?\\# ?", "");

                abc = abc.replace("strong", "");

                map1.put(KEY_DESC, abc);

                menuItems.add(map1);
            }

            return null;
        }

    }

    private class MyAsync1 extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {

            map1 = null;
            menuItems = null;
            ai = 0;

            URL = "http://www.dailyausaf.com/feed/";

            super.onPreExecute();

        }

        @Override
        protected void onPostExecute(Void result) {

            si = menuItems.size();

            testarray2 = new String[si];
            testarray3 = new String[si];

            for (HashMap<String, String> map : menuItems) {

                // String key = mapEntry.getKey();
                String value = map.get(KEY_NAME);
                String value1 = map.get(KEY_DESC);

                testarray2[ai] = value;
                testarray3[ai] = value1;

                ai++;

            }

            List<String> list = new ArrayList<String>(Arrays.asList(testarray));
            list.addAll(Arrays.asList(testarray2));

            c = new String[list.size()];
            c = list.toArray(c);

            List<String> list1 = new ArrayList<String>(
                    Arrays.asList(testarray1));
            list1.addAll(Arrays.asList(testarray3));

            c1 = new String[list1.size()];
            c1 = list1.toArray(c1);

            is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            disable = 1;
            listviewmethodausaf();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            menuItems = new ArrayList<HashMap<String, String>>();

            parser1 = new CopyOfXMLParser();
            xml = parser1.getXmlFromUrl(URL); // getting XML
            doc = parser1.getDomElement(xml); // getting DOM element

            n2 = doc.getElementsByTagName(KEY_ITEM);

            li = n2.getLength();

            for (int i = 0; i < n2.getLength(); i++) {
                // creating new HashMap
                map1 = new HashMap<String, String>();
                e = (Element) n2.item(i);

                map1.put(KEY_ID, parser1.getValue(e, KEY_ID));
                map1.put(KEY_NAME, parser1.getValue(e, KEY_NAME));
                map1.put(KEY_COST, parser1.getValue(e, KEY_COST));

                title = (Element) e.getElementsByTagName("description").item(0);

                titleCDATA = (CharacterData) title.getChildNodes().item(0);

                abc = (titleCDATA.getData());

                abc = abc.replace("<p>", "");
                abc = abc.replace("<b>", "");
                abc = abc.replace("&nbsp;", "");
                abc = abc.replace("</strong>", "");

                abc = abc.replace("<strong class='location'>", "");

                abc = abc.replace("<p align=", "");

                abc = abc.replace("right", "");

                abc = abc.replace(":&nbsp;", "");
                abc = abc.replace("</p>", "");

                abc = abc.replace("a", "");

                abc = abc.replace("b", "");

                abc = abc.replace("c", "");

                abc = abc.replace("d", "");

                abc = abc.replace("<", "");
                abc = abc.replace(">", "");
                abc = abc.replaceAll("\"", "");

                abc = abc.replace("_", "");
                abc = abc.replace("/", "");
                abc = abc.replace("+", "");
                abc = abc.replace("-", "");
                abc = abc.replace("$", "");
                abc = abc.replace("&", "");
                abc = abc.replaceAll("\\<.*?\\> ?", "");

                abc = abc.replaceAll("\\<.*?\\> ?", "");

                abc = abc.replaceAll("\\;.*?\\# ?", "");

                abc = abc.replaceAll("[a-zA-Z]", "");

                abc = abc.replace("%", "");

                // for change

                abc = abc.replaceAll("\\=.*?", "");

                abc = abc.replace("strong", "");

                map1.put(KEY_DESC, abc);

                menuItems.add(map1);
            }

            return null;
        }

    }

    private void listviewmethodausaf() {
        // TODO Auto-generated method stub
        adapter = new Customlistadapter(this, c);

        lv.setAdapter(adapter);

        if (par == 0) {

            par = par + 1;

        }

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                if (disable == 1) {

                    // getting values from selected ListItem
                    String name = ((TextView) view.findViewById(R.id.name))
                            .getText().toString();
                    String cost = ((TextView) view.findViewById(R.id.cost))
                            .getText().toString();
                    String description = c1[position];

                    Intent in = new Intent(getApplicationContext(),
                            SingleMenuItemActivity.class);
                    in.putExtra("name", description);
                    in.putExtra(KEY_COST, cost);
                    in.putExtra(KEY_DESC, description);
                    startActivity(in);

                }

            }
        });

    }

    private void listviewmethod() {
        // TODO Auto-generated method stub
        adapter = new Customlistadapter(this, testarray);

        lv.setAdapter(adapter);

        if (par == 0) {

            par = par + 1;

        }

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                if (disable == 1) {

                    // getting values from selected ListItem
                    String name = ((TextView) view.findViewById(R.id.name))
                            .getText().toString();
                    String cost = ((TextView) view.findViewById(R.id.cost))
                            .getText().toString();
                    String description = c1[position];

                    Intent in = new Intent(getApplicationContext(),
                            SingleMenuItemActivity.class);
                    in.putExtra("name", description);
                    in.putExtra(KEY_COST, cost);
                    in.putExtra(KEY_DESC, description);
                    startActivity(in);

                }

            }
        });

    }

    public class Customlistadapter extends ArrayAdapter {

        String[] color_names;

        Context context;

        public Customlistadapter(Context azkar, String[] text) {
            super(azkar, R.layout.list_item, text);

            this.color_names = text;

            this.context = azkar;
        }

        @SuppressLint("ViewHolder")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View single_row = inflater.inflate(R.layout.list_item, null, true);
            TextView textView = (TextView) single_row.findViewById(R.id.name);
            textView.setTextSize(s);

            textView.setText(color_names[position]);

            return single_row;
        }
    }

}

这里我使用两个异步类名作为

  1. 私有(private)类 MyAsync
  2. 私有(private)类 MyAsync1

第二个 Async 类在第一个 Async 类结果显示后执行。 如何在一个 Activity 中并行运行两个 Async 类?

最佳答案

以这种方式执行异步任务

new MyAsync().execute(AsyncTask.THREAD_POOL_EXECUTOR);
new MyAsync1().execute(AsyncTask.THREAD_POOL_EXECUTOR)

关于java - 我想在 android 应用程序中实现 AsyncTask 并行执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28736169/

相关文章:

android - Android SDK中的 "tools.jar"到底是什么?

c# - Winforms Thread Application Hang(后台工作线程)

c# - 使用多线程处理一组数据库记录的选项?

具有多线程的 Java Swing

java - enablePassThrough 不适用于 selenium 服务器 3.9.1

java - 从 XML 流读取命名空间的最佳方法(使用 Java)

Java JNA 将输出重定向到记录器

java - 有没有办法知道 JPanel 是否已完成加载其内容?

java - 我的共享首选项无法正确共享

android ndk 和 eclipse 给出了关于 c++ getline() 函数的不同错误信息