简体   繁体   English

如何在asynctask中同时运行asynctask?

[英]how run asynctask inside asynctask in the same time?

i have an web-based application that must retrive text in external database and image in server after one text retrived ,using following code for retrive text: 我有一个基于Web的应用程序,在检索到一个文本后,必须检索外部数据库中的文本和服务器中的图像,使用以下代码检索文本:

class BackgroundTaskOne extends AsyncTask<Void, Void, String>
{

    String json_url;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub          
        json_url="http://..some url../somefile.php";

    }

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

        String error="";
        try {
            URL url=new URL(json_url);

            HttpURLConnection httpUrlConnection=(HttpURLConnection) url.openConnection();

            InputStream inputStream=httpUrlConnection.getInputStream();
            BufferedReader bufferReader=new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder stringBuilder=new StringBuilder();

            while((JSON_STRINO=bufferReader.readLine())!=null){

                stringBuilder.append(JSON_STRINO+"\n");
                //add new textView  
            }

            bufferReader.close();
            inputStream.close();
            httpUrlConnection.disconnect();
            json_string=stringBuilder.toString().trim();
            return stringBuilder.toString().trim();
           // return "one row of data inserted..";
        } catch (MalformedURLException e) {
            error=e.getMessage()+" first";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            error=e.getMessage()+" sec";
        }
        return error;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }


    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        json_string=result;
        l=parse();


           int i=0;

           for(final String a[]:l){

               TextView t=new TextView(MainActivity.this);

               final String path=a[2]+".jpg";
                t.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
               t.setText(a[0]+" : "+a[1]+" i="+i);             
                t.setId(i);
                Reklam.addView(t);

                new LoadImage().execute(path);

            i++;
    }}}

i want to load image while loading first text and second image after second text in sequence but it loads all text then load all images , these folowing code for loading image: 我想在依次加载第一个文本和第二个文本后加载第二个图像的同时加载图像,但是它先加载所有文本,然后加载所有图像,这些用于加载图像的代码如下:

 private class LoadImage extends AsyncTask<String, String, Bitmap> {
    Bitmap bitmap;
    ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Loading Image ....");
        pDialog.show();

    }
     protected Bitmap doInBackground(String... args) {
         try {
               bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());

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

     protected void onPostExecute(Bitmap image) {

         if(image != null){
         ImageView img=new ImageView(MainActivity.this);
         img.setImageBitmap(image);
         img.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            Reklam.addView(img);
         pDialog.dismiss();

         }else{

         pDialog.dismiss();
         Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();

         }
     }
 }

if you want to run multiple thread parallely : 如果要并行运行多个线程:

 if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
        new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        new MyAsyncTask().execute();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM