2011-04-20 5 views
1

웹 사이트에서 이미지를 다운로드하고 SD 카드에 저장하는 코드가 있습니다. 어떤 이유로 2 개의 웹 주소를 보내면 첫 번째 이미지를 두 번 다운로드하고 두 번째 이미지 이름으로 저장하므로 웹 사이트에 image1 및 image2가있는 경우 코드는 image1을 두 번만 다운로드하고 저장합니다 SD 카드를 image2로 사용하면 누군가 내가 뭘 잘못하고 있는지 말해 줄 수 있습니까?SD 카드에 안드로이드 저장 이미지

public String getLocalLink(String image_URL, String imageName){ 
     /** This is what we do with this method: 
     * Go online, according to the link, get the content, call the method to save. 
     */ 

     ImageLink = image_URL; 
     URL ImageLinkURL; 

     try { 
      ImageLinkURL = new URL(ImageLink); 
      //URL url  = new URL(strURL); 
      if (!hasExternalStoragePublicPicture(imageName)) { 
       isImage = false; 
       new DownloadImageTask().execute(ImageLinkURL); 
       Log.v("log_tag", "if"); 
       isImage = true; 
       File sdImageMainDirectory = new File(Environment 
         .getExternalStorageDirectory(), getResources() 
         .getString(R.string.directory)); 
       sdImageMainDirectory.mkdirs(); 
       File file = new File(sdImageMainDirectory, imageName); 
       Log.v("log_tag", "Directory created"); 
      } 

     } catch (MalformedURLException e) { 
      Log.v(TAG, e.toString()); 
     } 
     return ("/sdcard/Hanud/”+imageName+".jpg"); 

    } 


    private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> { 
     // This class definition states that DownloadImageTask will take String 
     // parameters, publish Integer progress updates, and return a Bitmap 
     protected Bitmap doInBackground(URL... paths) { 
      URL url; 
      try { 
       url = paths[0]; 
       HttpURLConnection connection = (HttpURLConnection) url 
         .openConnection(); 
       int length = connection.getContentLength(); 
       InputStream is = (InputStream) url.getContent(); 
       byte[] imageData = new byte[length]; 
       int buffersize = (int) Math.ceil(length/(double) 100); 
       int downloaded = 0; 
       int read; 
       while (downloaded < length) { 
        if (length < buffersize) { 
         read = is.read(imageData, downloaded, length); 
        } else if ((length - downloaded) <= buffersize) { 
         read = is.read(imageData, downloaded, length 
           - downloaded); 
        } else { 
         read = is.read(imageData, downloaded, buffersize); 
        } 
        downloaded += read; 
        publishProgress((downloaded * 100)/length); 
       } 
       Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, 
         length); 
       if (bitmap != null) { 
        Log.i(TAG, "Bitmap created"); 
       } else { 
        Log.i(TAG, "Bitmap not created"); 
       } 
       is.close(); 
       return bitmap; 
      } catch (MalformedURLException e) { 
       Log.e(TAG, "Malformed exception: " + e.toString()); 
      } catch (IOException e) { 
       Log.e(TAG, "IOException: " + e.toString()); 
      } catch (Exception e) { 
       Log.e(TAG, "Exception: " + e.toString()); 
      } 
      return null; 

     } 

     protected void onPostExecute(Bitmap result) { 
      String name = ImageLink.substring(ImageLink 
        .lastIndexOf("/") + 1); 
      if (result != null) { 
       hasExternalStoragePublicPicture(name); 
       saveToSDCard(result, name); 
       isImage = true; 

      } else { 
       isImage = false; 

      } 
     } 
    } 

    public void saveToSDCard(Bitmap bitmap, String name) { 
     boolean mExternalStorageAvailable = false; 
     boolean mExternalStorageWriteable = false; 
     String state = Environment.getExternalStorageState(); 
     if (Environment.MEDIA_MOUNTED.equals(state)) { 
      mExternalStorageAvailable = mExternalStorageWriteable = true; 
      Log.v(TAG, "SD Card is available for read and write " 
        + mExternalStorageAvailable + mExternalStorageWriteable); 
      saveFile(bitmap, name); 
     } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
      mExternalStorageAvailable = true; 
      mExternalStorageWriteable = false; 
      Log.v(TAG, "SD Card is available for read " 
        + mExternalStorageAvailable); 
     } else { 
      mExternalStorageAvailable = mExternalStorageWriteable = false; 
      Log.v(TAG, "Please insert a SD Card to save your image " 
        + mExternalStorageAvailable + mExternalStorageWriteable); 
     } 
    } 

    private void saveFile(Bitmap bitmap, String name) { 

     String filename = name; 
     ContentValues values = new ContentValues(); 
     File sdImageMainDirectory = new File(Environment 
       .getExternalStorageDirectory(), getResources().getString(
       R.string.directory)); 
     sdImageMainDirectory.mkdirs(); 
     File outputFile = new File(sdImageMainDirectory, filename); 
     values.put(MediaStore.MediaColumns.DATA, outputFile.toString()); 
     values.put(MediaStore.MediaColumns.TITLE, filename); 
     values.put(MediaStore.MediaColumns.DATE_ADDED, System 
       .currentTimeMillis()); 
     values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png"); 
     Uri uri = this.getContentResolver().insert(
       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 

       values); 
     try { 
      OutputStream outStream = this.getContentResolver() 
        .openOutputStream(uri); 
      bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream); 

      outStream.flush(); 
      outStream.close(); 

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

    private boolean hasExternalStoragePublicPicture(String name) { 
     File sdImageMainDirectory = new File(Environment 
       .getExternalStorageDirectory(), getResources().getString(
       R.string.directory)); 
     File file = new File(sdImageMainDirectory, name); 
     if (file != null) { 
      file.delete(); 
     } 

     return file.exists(); 
    } 

답변

0

귀하의 사례에 대한 테스트를 마쳤습니다. 나의 예제는 매우 간단하다, 나는 무대에 버튼을 넣었다. 버튼을 클릭하면 두 개의 그림을 다운로드하기 위해 두 개의 asynctask가 시작됩니다. 내 sdcard에 폴더를 만듭니다. 테스트를 마치면 폴더에 두 장의 사진을 얻을 수 있습니다.

내가 코드를 확인한 후, 당신은 두 번 getLocalLink를 호출 할 때 두 번에 할당 된 클래스 변수 의 ImageLink을 가지고 같아요. 따라서 이미지는 두 번째 이미지 이름 파일에 저장됩니다.

본인의 예를 확인할 수 있으며 요구 사항에 부합합니다. 여러 개의 asyncTask를 작성하여 여러 개의 이미지를 다운로드 할 수 있습니다. AsyncTask 부분 만 확인하십시오.

http://jmsliu.com/1929/android-progress-dialog-example.html

관련 문제