暂停一个类并在android中启动另一个类,反之亦然

时间:2013-09-05 13:36:43

标签: java android multithreading bitmap download

我在android中的初学者。 我在2 .java文件中有2个类。第一:Mainacivity和第二:ImageDownloader。 imagedownloader用它的函数getBitmapFromURL(String url)下载位图,我给这个函数字符串,它运行良好,但我想一个接一个地下载超过1个位图。 我的主要活动:

public class MainActivity extends Activity implements View.OnClickListener 
{
private Button download, downloadBG, save;
private ImageView img;
private ProgressBar pb;
private EditText etUrl;
private TextView percent;
private ImageDownloader mDownloader;
private static Bitmap bmp;
private FileOutputStream fos;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initViews();
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);
}

/*--- initialize layout compinents ---*/
private void initViews() {

    download = (Button) findViewById(R.id.btnDownload);
    downloadBG = (Button) findViewById(R.id.btnDownloadBackground);
    save = (Button) findViewById(R.id.btnSave);
    /*--- we are using 'this' because our class implements the OnClickListener ---*/
    download.setOnClickListener(this);
    downloadBG.setOnClickListener(this);
    save.setOnClickListener(this);
    save.setEnabled(false);
    img = (ImageView) findViewById(R.id.image);
    img.setScaleType(ScaleType.CENTER_CROP);
    pb = (ProgressBar) findViewById(R.id.pbDownload);
    pb.setVisibility(View.INVISIBLE);
    etUrl = (EditText) findViewById(R.id.etUrl);
    percent = (TextView) findViewById(R.id.tvPercent);
    percent.setVisibility(View.INVISIBLE);

}

@Override
public void onClick(View v) {
    /*--- determine which button was clicked ---*/
    switch (v.getId()) 
            {

    case R.id.btnDownload:
            {
        /*--- we use trim() to remove whitespaces which could be entered ---*/

            bmp = ImageDownloader.getBitmapFromURL(URLbuilder(0, 0,       0));   
            img.setImageBitmap(bmp);
            save.setEnabled(true);

        break;
             }

    case R.id.btnDownloadBackground:

        for(int a = 0 ; a < 4 ; a++)
        {
        /*--- check whether there is some Text entered ---*/
    /*--- instantiate our downloader passing it required components ---*/
            mDownloader = new ImageDownloader(URLbuilder(a, a, a), a,pb, save, img, percent, MainActivity.this, bmp, new ImageLoaderListener() {
                @Override
                public void onImageDownloaded(Bitmap bmp) {
                    MainActivity.bmp = bmp;
         /*--- here we assign the value of bmp field in our Loader class 
                   * to the bmp field of the current class ---*/    
                }
                });

            /*--- we need to call execute() since nothing will happen otherwise ---*/
            mDownloader.execute();

        }


        break;
    }

}



public String URLbuilder(int x , int y , int z)
{
    String myurl = "http://khm0.google.com/kh/v=132&hl=EN&x={0}&y={1}&z={2}&s="; 
    String.format(myurl, x,y,z);
    return String.format(myurl, x,y,z);
}
}

如果我点击DownloadBackground按钮,它应该从它的url下载4位图。 我知道每次下载需要一些时间,但我无法停止此功能,直到第一次位图下载。 我的imagedownloader:

public class ImageDownloader extends AsyncTask<Void, Integer, Void> 
{

private ProgressBar pb;
private String url;
private Button save;
private Context c;
private int progress;
private ImageView img;
private Bitmap bmp;
private TextView percent;
private ImageLoaderListener listener;
FileOutputStream fos;
int Counter = 0;


/*--- constructor ---*/
public ImageDownloader(String url,int counter, ProgressBar pb, Button save,
        ImageView img, TextView percent, Context c, Bitmap bmp, ImageLoaderListener listener) {
/*--- we need to pass some objects we are going to work with ---*/
    this.url = url;
    this.pb = pb;
    this.save = save;
    this.c = c;
    this.img = img;
    this.percent = percent;
    this.bmp = bmp;
    this.listener = listener;
    //this.Counter = Integer.toString(counter);
}

/*--- we need this interface for keeping the reference to our Bitmap from the MainActivity. 
 *  Otherwise, bmp would be null in our MainActivity*/
public interface ImageLoaderListener {

    void onImageDownloaded(Bitmap bmp);

    }

@Override
protected void onPreExecute() {

    progress = 0;
    pb.setVisibility(View.VISIBLE);
    percent.setVisibility(View.VISIBLE);
    Toast.makeText(c, "starting download", Toast.LENGTH_SHORT).show();

    super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {

    bmp = getBitmapFromURL(url);

    while (progress < 100) {

        progress += 1;

        publishProgress(progress);

        /*--- an image download usually happens very fast so you would not notice 
         * how the ProgressBar jumps from 0 to 100 percent. You can use the method below 
         * to visually "slow down" the download and see the progress bein updated ---*/

      //SystemClock.sleep(200);

    }

    return null;
}

@Override
protected void onProgressUpdate(Integer... values) {

/*--- show download progress on main UI thread---*/
    pb.setProgress(values[0]);
    percent.setText(values[0] + "%");

    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(Void result) {

    if (listener != null) {
        listener.onImageDownloaded(bmp);
        }
    img.setImageBitmap(bmp);
    saveImageToSD();
    save.setEnabled(true);
    Toast.makeText(c, "download complete", Toast.LENGTH_SHORT).show();

    super.onPostExecute(result);
}

public static Bitmap getBitmapFromURL(String link) 
{
    /*--- this method downloads an Image from the given URL, 
     *  then decodes and returns a Bitmap object
     ---*/
    try {
        URL url = new URL(link);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);

        return myBitmap;

    } catch (IOException e) {
        e.printStackTrace();
        Log.e("getBmpFromUrl error: ", e.getMessage().toString());
        return null;
    }
}






private void saveImageToSD() 
{

    /*--- this method will save your downloaded image to SD card ---*/

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    /*--- you can select your preferred CompressFormat and quality. 
     * I'm going to use JPEG and 100% quality ---*/
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    /*--- create a new file on SD card ---*/
    File file = new File(Environment.getExternalStorageDirectory()
            + File.separator + "myDownloadedImage" + Integer.toString(Counter) + ".jpg");
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    /*--- create a new FileOutputStream and write bytes to file ---*/
    try {
        fos = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        fos.write(bytes.toByteArray());
        fos.close();

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

    Counter++;

}

我需要在主要活动的onclick方法中停止循环,直到每个图像下载。我做了我知道的每一件事,但每次都崩溃了。 后来我必须把图像下载器放在一个线程中,但我不知道如何停止线程一段时间。 请帮助我。 TY

1 个答案:

答案 0 :(得分:0)

您可以使用处理程序

new Handler().postDelayed(new Runnable(){
public void run() {
    //some job to do delayed 3s
}}, 3000);

希望它有所帮助!