2013-03-09 1 views
1

에서 다운로드 이미지에서 onCreate()에서 호출되지 않습니다 나는 그대로 내 문제도, 내가 This을 보았다 내 에뮬레이터 웹에서 images을 다운로드하려면 안드로이드에 새로운 해요.AsyncTask를이 <> 웹

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    new MyAsnyc().execute(); 
} 

public class MyAsnyc extends AsyncTask<Void, Void,Void>{ 
    public File file ; 
    InputStream is; 
    protected void inBackground() throws IOException{ 

     File path = Environment.getExternalStoragePublicDirectory(
       Environment.DIRECTORY_PICTURES); 
     file = new File(path, "DemoPicture.jpg"); 
     try{ 
      // Make sure the Pictures directory exists. 
      path.mkdirs(); 

      URL url = new  URL(BASE_URL); 
      /* Open a connection to that URL. */ 
      URLConnection ucon = url.openConnection(); 

      /* 
      * Define InputStreams to read from the URLConnection. 
      */ 
      is = ucon.getInputStream(); 

      OutputStream os = new FileOutputStream(file); 
      byte[] data = new byte[is.available()]; 
      is.read(data); 
      Log.d("MY_TAG>>>", "Picture is Readable..."); 
      os.write(data); 
      Log.d("MY_TAG>>>", "Picture is Saved..."); 
      is.close(); 
      os.close(); 

     } 
     catch (IOException e) { 
      Log.d("ImageManager", "Error: " + e); 
     } 
    } 
    @Override 
    protected Void doInBackground(Void... params) { 
     // TODO Auto-generated method stub 

     try { 
      inBackground(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return null; 
    } 
    protected void onPostExecute() 
    { 

     try 
     { 
      // Tell the media scanner about the new file so that it is 
      // immediately available to the user. 

      MediaScannerConnection.scanFile(null, 
        new String[] { file.toString() }, null, 
        new MediaScannerConnection.OnScanCompletedListener() { 
       public void onScanCompleted(String path, Uri uri) { 
        Log.i("ExternalStorage", "Scanned " + path + ":"); 
        Log.i("ExternalStorage", "-> uri=" + uri); 
       } 
      }); 
     } 
     catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 
} 

}

을하지만 내 AsyncTask 중 하나가이 문제를 해결하는 방법과 웹에서 이미지를 다운로드하는 방법 좀 도와주세요 호출되지 않습니다 :하지만 난 이런 짓을했는지.

+0

왜 2 개의 doInBackground() 메소드가 있습니까? 'protected void doInBackground()는 IOException을 던집니다. {'and'protected Void doInBackground (void ... params) {' –

+0

[link] (http://stackoverflow.com/questions/9762057/how-to- url-to-your-android-app에서 download-file-image-download); –

+0

웹에서 이미지 만 다운로드 하시겠습니까? '예'아니면'아니오'입니까? '예'라고 대답한다면 내 눈에는 다른 방법이 있습니다! reply –

답변

0

을! 귀하의 장치/에뮬레이터에 이미지를 다운로드하려면 이것을 시도해야합니다 !!

먼저 만들기 Class로 :

public class DownloadImage {  

public static File getImage(String imageUrl, String fileName){ 
    File file = null; 
    try { 
     //set the download URL, a url that points to a file on the internet 
     //this is the file to be downloaded   
     URL url = new URL(imageUrl); 
     Log.d("INFORMATION..", "FILE FOUNDED...."); 
     //create the new connection 
     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

     //set up some things on the connection 
     urlConnection.setRequestMethod("GET"); 
     urlConnection.setDoOutput(true); 

     //and connect! 
     urlConnection.connect(); 
     Log.d("INFORMATION..", "FILE CONECTED...."); 
     //set the path where we want to save the file 
     //in this case, going to save it on the root directory of the 
     //sd card. 
     File SDCardRoot = Environment.getExternalStorageDirectory(); 
     //create a new file, specifying the path, and the filename 
     //which we want to save the file as. 
     file = new File(SDCardRoot, fileName); 

     //this will be used to write the downloaded data into the file we created 
     FileOutputStream fileOutput = new FileOutputStream(file); 
     Log.d("INFORMATION..", "WRINTING TO FILE DOWNLOADED...." + file); 
     //this will be used in reading the data from the internet 
     InputStream inputStream = urlConnection.getInputStream(); 

     //this is the total size of the file 
     int totalSize = urlConnection.getContentLength(); 
     //variable to store total downloaded bytes 
     int downloadedSize = 0; 

     //create a buffer... 
     byte[] buffer = new byte[1024]; 
     int bufferLength = 0; //used to store a temporary size of the buffer 

     //now, read through the input buffer and write the contents to the file 
     while ((bufferLength = inputStream.read(buffer)) > 0) { 
      //add the data in the buffer to the file in the file output stream (the file on the sd card 
      fileOutput.write(buffer, 0, bufferLength); 
      //add up the size so we know how much is downloaded 
      downloadedSize += bufferLength; 
      Log.d("INFORMATION..", "FILE DOWNLOADED...."); 
      //this is where you would do something to report the prgress, like this maybe 
      //updateProgress(downloadedSize, totalSize); 

     } 
     //close the output stream when done 
     fileOutput.close(); 
     Log.d("INFORMATION..", "FILE DOWNLOADING COMPLETED...."); 
     //catch some possible errors... 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return file; 
} 
) 

전화 같은 MainActivity.javaDownloadImage.getImage(String imageUrl, String fileName) :

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    ImageView imageView = (ImageView) findViewById(R.id.imageView1); 

    String url = "http://4.bp.blogspot.com/-8v_k_fOcfP8/UQIL4ufghBI/AAAAAAAAEDo/9ffRRTM9AnA/s1600/android-robog-alone.png"; 

    String file = DownloadImage.getImage(url, "My Image.jpg").toString(); 

    // Get file path on device and set it to imageView 
    Bitmap bitmap = BitmapFactory.decodeFile(file); 
    imageView.setImageBitmap(bitmap); 
} 
} 

나는이 당신의 필요에 따라 작동합니다 희망!

2

doInBackground() 대신에 doInBackground(Void... params)을 재귀 호출합니다. 후자의 이름을 다른 것으로 바꾼 후 doInBackground(Void... params)에서 호출하십시오.

+0

'doInBackground()'의 이름을'inBackground()'로 바 꾸었으나 아직 결과를 얻지 못했습니다 –

+0

유감스럽게 생각합니다. 그러나 그렇게하지 않는 것이 좋습니다! logcat은'Log' 호출이나'printStackTrace'의 에러를 보여줍니까? – Aert

+0

안녕하세요.'logcat'에 메시지가 없습니다 –

0

같은 doInBackground의 모든 실행 : 좋아

public class MyAsnyc extends AsyncTask<Void, Void,Void>{ 
    public File file ; 
    InputStream is; 

    @Override 
    protected Void doInBackground(Void... params) { 
     // TODO Auto-generated method stub 

     try{ 
     File path = Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_PICTURES); 
     file = new File(path, "DemoPicture.jpg"); 

       // Make sure the Pictures directory exists. 
       path.mkdirs(); 

       URL url = new  URL(BASE_URL); 
       /* Open a connection to that URL. */ 
       URLConnection ucon = url.openConnection(); 

       /* 
       * Define InputStreams to read from the URLConnection. 
       */ 
       is = ucon.getInputStream(); 

       OutputStream os = new FileOutputStream(file); 
       byte[] data = new byte[is.available()]; 
       is.read(data); 
       Log.d("MY_TAG>>>", "Picture is Readable..."); 
       os.write(data); 
       Log.d("MY_TAG>>>", "Picture is Saved..."); 
       is.close(); 
       os.close(); 

      } 
      catch (IOException e) { 
       Log.d("ImageManager", "Error: " + e); 
      } 

     return null; 
    } 

    protected void onPostExecute() 
    { 

    try 
    { 
     // Tell the media scanner about the new file so that it is 
     // immediately available to the user. 

     MediaScannerConnection.scanFile(null, 
       new String[] { file.toString() }, null, 
       new MediaScannerConnection.OnScanCompletedListener() { 
      public void onScanCompleted(String path, Uri uri) { 
       Log.i("ExternalStorage", "Scanned " + path + ":"); 
       Log.i("ExternalStorage", "-> uri=" + uri); 
      } 
     }); 
    } 
    catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    } 

} 
관련 문제