需要线程教程

时间:2011-09-25 14:43:33

标签: android

我有一个应用程序,它从互联网上加载图像并使用gallery widget和imageview的组合进行显示。我想将下载图像部分放到一个单独的线程中,但即使经过一些谷歌搜索,我也不知道该怎么做。以下是我的代码,任何人都可以请帮助我。提前谢谢。

package com.example.gallery;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

public class GalleryActivity extends Activity {
public Bitmap[] bmps;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Gallery gal = (Gallery)findViewById(R.id.gallery);

    final ImageView iv = (ImageView)findViewById(R.id.imageView);

    gal.setAdapter(new ImageAdapter(this));

    gal.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
            View v, int position, long id) {        

            Bitmap bm = bmps[position];
            if(bm.getHeight() > 800 || bm.getWidth() > 600) 
            {
                Bitmap rbm = Bitmap.createScaledBitmap(bm, bm.getWidth()/2, bm.getHeight()/2, true);
                iv.setImageBitmap(rbm);
            }
            else
            {
                iv.setImageBitmap(bm);
            }

        }
    });
}

public void initBmps(int length)
{
    bmps = new Bitmap[length];
}

public void setBmps(Bitmap bm, int pos)
{
    bmps[pos] = bm;
}

public class ImageAdapter extends BaseAdapter
{
    int mGalleryItemBackground;
    private Context mContext;

    private String[] mImageIds = {"http://4.bp.blogspot.com/-bQQ6UcJhpoA/TfOeymYKMeI/AAAAAAAAAIo/30kj0KUAgxo/s1600/snsd1.jpg",
                                    "http://www.sweetslyrics.com/images/img_gal/13192_snsd-group-31.jpg", 
                                    "http://kojaproductions.files.wordpress.com/2008/12/snsd_teases_kjp.jpg",
                                    "http://solar.envirohub.net/images/solar-power.jpg",
                                    "http://scm-l3.technorati.com/11/05/27/35419/solar-power.jpg?t=20110527104336",
                                    "http://www.solarstorms.org/Pictures/GridMap.gif",
                                    "http://static.electro-tech-online.com/imgcache/11039-power%20lines.jpg"};


    public ImageAdapter(Context c) 
    {
        mContext = c;
        TypedArray a = mContext.obtainStyledAttributes(R.styleable.Theme);
        mGalleryItemBackground = a.getResourceId(R.styleable.Theme_android_galleryItemBackground, 0);
        initBmps(mImageIds.length);
        a.recycle();
    }

    public int getCount()
    {
        return mImageIds.length;
    }

    public Object getItem(int position)
    {
        return position;
    }

    public long getItemId(int position)
    {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
        ImageView i = new ImageView(mContext);

            DownloadImageTask down = new DownloadImageTask();
            down.excecute(mImageIds[position]);

            if(down..getStatus() == AsyncTask.Status.FINISHED)
            {

              Bitmap rbm = Bitmap.createScaledBitmap(bm, 200, 200, true);

              i.setImageBitmap(rbm);
              i.setLayoutParams(new Gallery.LayoutParams(150, 150));
              i.setScaleType(ImageView.ScaleType.FIT_XY);
              i.setBackgroundResource(mGalleryItemBackground);
            }
            return i;
    }

 private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... url) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), url[0], Toast.LENGTH_SHORT).show();
            URL aURL;
            Bitmap bm = null;
            try {
                aURL = new URL(url[0]);
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                bm = BitmapFactory.decodeStream(bis);
                //setBmps(bm, position);
                bis.close();
                is.close();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute (Bitmap result) {
            setBm(result);
        }

    }

}
}

3 个答案:

答案 0 :(得分:0)

我建议您使用AsyncTask进行图像下载,这就是我一直在使用的内容:

http://developer.android.com/reference/android/os/AsyncTask.html

http://developer.android.com/resources/articles/painless-threading.html

答案 1 :(得分:0)

答案 2 :(得分:0)

好的

以下是一些ImageDownloader引用。

他们将图像下载委托给AsyncTask