2011-04-20 5 views
1

J'ai un code qui télécharge une image à partir d'un site Web et l'enregistre sur la carte SD. Lorsque j'envoie 2 adresses Web pour une raison quelconque, il ne télécharge que deux fois la première image et les enregistre toutes deux avec le deuxième nom de l'image. S'il y a image1 et image2 sur le site Web, le code télécharge deux fois Carte SD comme image2 peut s'il vous plaît quelqu'un me dire ce que je fais mal?Android Enregistrement de l'image deux fois sur la carte 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(); 
    } 

Répondre

0

J'ai effectué un test sur votre étui. Mon exemple est très simple, je mets un bouton sur la scène. Lorsque je clique sur le bouton, je vais commencer deux asynctask pour télécharger deux images. Je crée un dossier dans ma carte SD. Après le test, je peux obtenir deux images dans le dossier.

Après avoir vérifié votre code, je suppose que vous avez une variable classe ImageLink, qui est attribué deux fois lorsque vous appelez getLocalLink deux fois. Ainsi, l'image sera stockée dans votre deuxième fichier de nom d'image.

Vous pouvez vérifier mon exemple, cela fonctionne pour vos besoins. Vous pouvez créer plusieurs asyncTask pour télécharger plusieurs images. Veuillez simplement vérifier la partie AsyncTask.

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

Questions connexes