2016-02-21 131 views
-1

我想從URL下載的圖像並保存到內部存儲 我有這樣的代碼,但如果我的手機不具備外部存儲的圖像不能被下載下載圖像到內部存儲器

Bitmap b=null; 
    URL url; 
    InputStream iStream=null; 
    File tmpFile; 
    try { 
     url = new URL(strURL); 
     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();    
     urlConnection.connect(); 
     iStream = urlConnection.getInputStream(); 
     File cacheDirectory = context.getCacheDir(); 
     tmpFile = new File(cacheDirectory.getPath() + "/news.png"); 
     FileOutputStream fOutStream = new FileOutputStream(tmpFile); 
     b = BitmapFactory.decodeStream(iStream); 
     b.compress(Bitmap.CompressFormat.PNG,100, fOutStream); 

     fOutStream.flush(); 
     fOutStream.close(); 
    } 
    catch(Exception ee) 
    { 

    } 
    return b; 

做你幫我從url下載映像到內部存儲內置存儲內存

+1

我在這裏沒有看到問題。 –

回答

0

你首先需要檢查手機是否有外部目錄。 android documentation已經有這樣做的代碼。

/* Checks if external storage is available for read and write */ 
public boolean isExternalStorageWritable() { 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state)) { 
     return true; 
    } 
    return false; 
} 

/* Checks if external storage is available to at least read */ 
public boolean isExternalStorageReadable() { 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state) || 
     Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
     return true; 
    } 
    return false; 
} 
+0

謝謝,但我想下載鏡像到內部存儲(我的設備沒有外部存儲) – soheila

+1

嘗試做這個'tmpFile = new File(context.getFilesDir(),「news.png」);'或者看看這個[文檔](http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage)並根據文檔getCacheDir返回內部存儲......有關如何將文件保存在內部存儲中的信息,請參閱此文檔教程[鏈接](http://codetheory.in/android-saving-files-on-internal-and-external-storage/) –

+0

你可以給我發送完整的代碼嗎? – soheila