2013-09-05 1 views
1

메신저가 시작됩니다. 2 .java 파일에 2 개의 클래스가 있습니다. 첫 번째 : Mainacivity 및 두 번째 : ImageDownloader. imagedownloader는 getBitmapFromURL (String url) 함수를 사용하여 비트 맵을 다운로드합니다.이 함수에 문자열을 지정하면 잘 작동하지만 1 비트 맵을 하나 이상 다운로드하고 싶습니다. 내 주요 활동 : 내가 DownloadBackground 버튼을 클릭하면이 URL이의에서한 클래스를 일시 중지하고 다른 클래스를 시작하면 안드로이드에서

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); 
} 
} 

는 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++; 

} 

내가 각 이미지를 다운로드 할 때까지의 주요 활동에 온 클릭 방식으로 루프 중지해야합니다. 나는 내가 아는 모든 것을했지만 추락 할 때마다했다. 나중에 스레드에 이미지 다운 로더를 넣어야하지만 잠시 동안 스레드를 중지하는 방법을 모른다. pls 나를 도와주세요.

답변

0

타이 당신은

는 희망이 도움이 핸들러

new Handler().postDelayed(new Runnable(){ 
public void run() { 
    //some job to do delayed 3s 
}}, 3000); 
을 사용할 수 있습니다!

관련 문제