Android读取SD/USB空间大小以及内容

  Android.os下的StatFs类主要用来获取文件系统的状态,能够获取sd卡的大小和剩余空间,获取系统内部空间也就是/system的大小和剩余空间等等。


  看下读取sd卡的:

   Java代码
  1. void  readSDCard() {  
  2.         String state = Environment.getExternalStorageState();  
  3.         if (Environment.MEDIA_MOUNTED.equals(state)) {  
  4.             File sdcardDir = Environment.getExternalStorageDirectory();  
  5.             StatFs sf = new  StatFs(sdcardDir.getPath());  
  6.             long  blockSize = sf.getBlockSize();  
  7.             long  blockCount = sf.getBlockCount();  
  8.             long  availCount = sf.getAvailableBlocks();  
  9.             Log.d("" ,  "block大小:" + blockSize+ ",block数目:" + blockCount+ ",总大小:" +blockSize*blockCount/ 1024 + "KB" );  
  10.             Log.d("" ,  "可用的block数目::" + availCount+ ",剩余空间:" + availCount*blockSize/ 1024 + "KB" );  
  11.         }     
  12.     }  
  13. void readSDCard() {
  14.      String state = Environment.getExternalStorageState();
  15.      if(Environment.MEDIA_MOUNTED.equals(state)) {
  16.       File sdcardDir = Environment.getExternalStorageDirectory();
  17.       StatFs sf = new StatFs(sdcardDir.getPath());
  18.       long blockSize = sf.getBlockSize();
  19.       long blockCount = sf.getBlockCount();
  20.       long availCount = sf.getAvailableBlocks();
  21.       Log.d("", "block大小:"+ blockSize+",block数目:"+ blockCount+",总大小:"+blockSize*blockCount/1024+"KB");
  22.       Log.d("", "可用的block数目::"+ availCount+",剩余空间:"+ availCount*blockSize/1024+"KB");
  23.      }  
  24.     }   
复制代码
然后看下读取系统内部空间的:

   Java代码
  1.   void readSystem() {

  2.   File root = Environment.getRootDirectory();

  3.   StatFs sf = new StatFs(root.getPath());

  4.   long blockSize = sf.getBlockSize();

  5.   long blockCount = sf.getBlockCount();

  6.   long availCount = sf.getAvailableBlocks();

  7.   Log.d("" , "block大小:" + blockSize+ ",block数目:" + blockCount+ ",总大小:" +blockSize*blockCount/ 1024 + "KB" );

  8.   Log.d("" , "可用的block数目::" + availCount+ ",可用大小:" + availCount*blockSize/ 1024 + "KB" );

  9.   }

  10.   void readSystem() {

  11.   File root = Environment.getRootDirectory();

  12.   StatFs sf = new StatFs(root.getPath());

  13.   long blockSize = sf.getBlockSize();

  14.   long blockCount = sf.getBlockCount();

  15.   long availCount = sf.getAvailableBlocks();

  16.   Log.d("", "block大小:"+ blockSize+",block数目:"+ blockCount+",总大小:"+blockSize*blockCount/1024+"KB");

  17.   Log.d("", "可用的block数目::"+ availCount+",可用大小:"+ availCount*blockSize/1024+"KB");

  18.   }
复制代码

      StatFs获取的都是以block为单位的,这里我解释一下block的概念:


  1.硬件上的 block size, 应该是"sector size",linux的扇区大小是512byte

  2.有文件系统的分区的block size, 是"block size",大小不一,可以用工具查看

  3.没有文件系统的分区的block size,也叫“block size”,大小指的是1024 byte

  4.Kernel buffer cache 的block size, 就是"block size",大部分PC是1024

  5.磁盘分区的"cylinder size",用fdisk 可以查看。

  我们这里的block size是第二种情况,一般SD卡都是fat32的文件系统,block size是4096.

  这样就可以知道手机的内部存储空间和sd卡存储空间的总大小和可用大小了。
public class GetMediasInfo {
	
	private static final String TAG = "MediaInfoUtil";
	
	private static final String USB_PATH = "/storage/usbotg";
	private static final String USB_FILTER = "usbotg";
	private static final String SD_PATH = "/storage/sdcard1";
	private static final String SD_FILTER = "sdcard1";
	private static final String INTERNAL_PATH = "/storage/sdcard0";
	private static final String INTERNAL_FILTER = "sdcard0";
	
	public static final int PARAMETER_SOURCE_TYPE_INTERNAL = 0;
	public static final int PARAMETER_SOURCE_TYPE_SD = 1;
	public static final int PARAMETER_SOURCE_TYPE_USB = 2;
		
	public static final int PARAMETER_STORAGE_UNIT_MB = 3;
	public static final int PARAMETER_STORAGE_UNIT_GB = 4;
	
	public static final int RESULT_SOURCE_ERROR = -1;
	public static final int RESULT_INTERNAL_ERROR = -2;
	public static final int RESULT_PARAMETER_ERROR = -3;
	public static final int RESULT_INFO_NUMBER_ZERO = -4;
	public static final int RESULT_INFO_Resolver_NULL = -5;
		
	public static boolean storageExist(String path){
		
		try {
			File file = new File(path);
			if(null == file){
				return false;
			}
				
			File[] files = file.listFiles();
			if(null == files || files.length == 0){
				return false;
			}
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean getUsbState(){
		return storageExist(USB_PATH);
	}
	
	public static boolean getSdState(){
		return storageExist(SD_PATH);
	}
	
    @SuppressLint("NewApi") 
    public static double getStorageTotalSize(int sourceType, int unit){
		
		String path = null;
		if( PARAMETER_SOURCE_TYPE_SD == sourceType){
			
			if(!storageExist(SD_PATH)){
				return RESULT_SOURCE_ERROR;
			}
			path = SD_PATH;
		}else if( PARAMETER_SOURCE_TYPE_USB == sourceType){
			
			if(!storageExist(USB_PATH)){
				return RESULT_SOURCE_ERROR;
			}
			path = USB_PATH;
		}else{
			
			return RESULT_PARAMETER_ERROR;
		}
		try {
			StatFs stat = new StatFs(path); 
			long blockSize = stat.getBlockSizeLong();
			long blockCount = stat.getBlockCountLong();
			double Total;
			
			if(unit == PARAMETER_STORAGE_UNIT_MB){
				
				Total = blockCount * blockSize / 1024 / 1024;
				Total = (double)Math.round(Total*10)/10;
				Log.w(TAG, "TotalSize:"+Total+"MB");
			}else if(unit == PARAMETER_STORAGE_UNIT_GB){
				
				Total = ( 10 * blockCount * blockSize / 1024 / 1024 / 1024 ) * 0.1;
				Total = (double)Math.round(Total*10)/10;
				Log.w(TAG, "TotalSize:"+Total+"GB");
			}else{
				
				Total = blockCount * blockSize / 1024 / 1024;
				Total = (double)Math.round(Total*10)/10;
				Log.w(TAG, "TotalSize:"+Total+"MB");
			}
					
			return Total;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
	
	@SuppressLint("NewApi")
	public static double getStorageAvailaleSize(int sourceType, int unit){
		//get used space size
		String path = null;
		if( PARAMETER_SOURCE_TYPE_SD == sourceType){
			
			if(!storageExist(SD_PATH)){
				return RESULT_SOURCE_ERROR;
			}
			path = SD_PATH;
		}else if( PARAMETER_SOURCE_TYPE_USB == sourceType){
			
			if(!storageExist(USB_PATH)){
				return RESULT_SOURCE_ERROR;
			}
			path = USB_PATH;
		}else{
			
			return RESULT_PARAMETER_ERROR;
		}
		try {
			StatFs stat = new StatFs(path); 
			long blockSize = stat.getBlockSizeLong();
			long availaleBlockCount = stat.getAvailableBlocksLong();
			
			double Total;
			
			if(unit == PARAMETER_STORAGE_UNIT_MB){
				
				Total = availaleBlockCount * blockSize / 1024 / 1024;
				Total = (double)Math.round(Total*10)/10;
				Log.w(TAG, "availaleSize:"+Total+"MB");
			}else if(unit == PARAMETER_STORAGE_UNIT_GB){
				
				Total = ( 10 * availaleBlockCount * blockSize / 1024 / 1024 / 1024 ) * 0.1;
				Total = (double)Math.round(Total*10)/10;
				Log.w(TAG, "availaleSize:"+Total+"GB");
			}else{
				
				Total = availaleBlockCount * blockSize / 1024 / 1024;
				Total = (double)Math.round(Total*10)/10;
				Log.w(TAG, "availaleSize:"+Total+"MB");
			}
					
			return Total;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
	
	public static int getMusicInfoSongNums(Context context,int sourceType){
		String pathFilter = " ";
		Uri queryUri;
		int Result_count = 0;
		
		if( PARAMETER_SOURCE_TYPE_SD == sourceType){
			if(!storageExist(SD_PATH)){
				return RESULT_SOURCE_ERROR;
			}
			pathFilter = SD_FILTER;
			queryUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

		}else if( PARAMETER_SOURCE_TYPE_USB == sourceType){
			if(!storageExist(USB_PATH)){
				return RESULT_SOURCE_ERROR;
			}
			pathFilter = USB_FILTER;
			queryUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_INTERNAL == sourceType){
			if(!storageExist(INTERNAL_PATH)){
				return RESULT_SOURCE_ERROR;
			}	
			pathFilter = INTERNAL_FILTER;
			queryUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
		}else{
			return RESULT_PARAMETER_ERROR;
		}

        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(queryUri, null,
                null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        
        int fileNum = cursor.getCount();
        Log.d(TAG,"cursor.getCount: "+fileNum);
        cursor.moveToFirst();
        Result_count = 0;

        for(int counter = 0; counter < fileNum; counter++){ 
            String path = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
            if(!path.contains(pathFilter)){
            	cursor.moveToNext();
            	continue;
            }
            Result_count++;
            cursor.moveToNext();
        }
        cursor.close();
        Log.d(TAG, "=====>Result_count1 is:"+Result_count);
        return Result_count;
	}
	
	
	
	public static int getMusicInfo(Context context,int sourceType, ArrayList<MusicInfo> infoList){
		
		String pathFilter = " ";
		Uri queryUri;
		int Result_count = 0;

		if( PARAMETER_SOURCE_TYPE_SD == sourceType){
			if(!storageExist(SD_PATH)){
				return RESULT_SOURCE_ERROR;
			}
			pathFilter = SD_FILTER;
			queryUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

		}else if( PARAMETER_SOURCE_TYPE_USB == sourceType){
			if(!storageExist(USB_PATH)){
				return RESULT_SOURCE_ERROR;
			}
			pathFilter = USB_FILTER;
			queryUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_INTERNAL == sourceType){
			if(!storageExist(INTERNAL_PATH)){
				return RESULT_SOURCE_ERROR;
			}	
			pathFilter = INTERNAL_FILTER;
			queryUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
		}else{
			return RESULT_PARAMETER_ERROR;
		}

        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(queryUri, null,
                null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

            if(cursor == null){
                Log.w(TAG, "query music result Cursor == null");
                return RESULT_INTERNAL_ERROR;
            }

            int fileNum = cursor.getCount();
            Log.d(TAG,"cursor.getCount: "+fileNum);
            cursor.moveToFirst();
            infoList.clear();
            for(int counter = 0; counter < fileNum; counter++){ 
                String path = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
                if(!path.contains(pathFilter)){
                	cursor.moveToNext();
                	continue;
                }

                MusicInfo info = new MusicInfo();
                info.setMusicId(cursor.getInt(cursor.getColumnIndex(BaseColumns._ID)));
                info.setTitle(cursor.getString(cursor.getColumnIndex(MediaColumns.TITLE)));
                info.setArtist(cursor.getString(cursor.getColumnIndex(AudioColumns.ARTIST)));
                info.setAlbum(cursor.getString(cursor.getColumnIndex(AudioColumns.ALBUM)));
                info.setAlbumId(cursor.getInt(cursor.getColumnIndex(AudioColumns.ALBUM_ID)));
                info.setDuration(cursor.getString(cursor.getColumnIndex(AudioColumns.DURATION)));
                info.setPath(cursor.getString(cursor.getColumnIndex(MediaColumns.DATA)));
                info.setSize(cursor.getString(cursor.getColumnIndex(MediaColumns.SIZE)));
                //info.setAlbumImage(getMusicAlbumImage(context,cursor.getString(cursor.getColumnIndex(AudioColumns.ALBUM_ID))));
                if(PARAMETER_SOURCE_TYPE_SD == sourceType){
                	info.setMusicResource(PARAMETER_SOURCE_TYPE_SD);
                }else if(PARAMETER_SOURCE_TYPE_USB == sourceType){
                	info.setMusicResource(PARAMETER_SOURCE_TYPE_USB);
                }              
                infoList.add(info);
                Result_count++;
                cursor.moveToNext();
            }
        cursor.close();
        return Result_count;
    }
	
	public static int getVideoInfoVideoNums(Context context,int sourceType){
		String pathFilter = " ";
		Uri queryUri;
		int Result_count = 0;

		if( PARAMETER_SOURCE_TYPE_SD == sourceType){
			
			if(!storageExist(SD_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = SD_FILTER;
			queryUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_USB == sourceType){
			
			if(!storageExist(USB_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = USB_FILTER;
			queryUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_INTERNAL == sourceType){
			
			if(!storageExist(INTERNAL_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = INTERNAL_FILTER;
			queryUri = MediaStore.Video.Media.INTERNAL_CONTENT_URI;
		}else{
			
			return RESULT_PARAMETER_ERROR;
		}

        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(queryUri, null,
                null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);


            if(cursor == null){
                Log.w(TAG, "query music result Cursor == null");
                return RESULT_INTERNAL_ERROR;
            }

            int fileNum = cursor.getCount();
            cursor.moveToFirst();
            Result_count = 0;
            for(int counter = 0; counter < fileNum; counter++){            	 
                String path = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
                if(!path.contains(pathFilter)){
                	cursor.moveToNext();
                	continue;
                }
                Result_count++;
                cursor.moveToNext();
            }
        cursor.close();
        Log.d(TAG, "=====>Result_count2 is:"+Result_count);
        return Result_count;
	}
	
	public static int getVideoInfo(Context context,int sourceType,ArrayList<VideoInfo> infoList){
		
		Log.d(TAG, "getVideoInfo");
		
		BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = false;
        options.inJustDecodeBounds = false; 
    	options.inSampleSize = 30;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		
		String pathFilter = " ";
		Uri queryUri;
		int Result_count = 0;

		if( PARAMETER_SOURCE_TYPE_SD == sourceType){
			
			if(!storageExist(SD_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = SD_FILTER;
			queryUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_USB == sourceType){
			
			if(!storageExist(USB_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = USB_FILTER;
			queryUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_INTERNAL == sourceType){
			
			if(!storageExist(INTERNAL_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = INTERNAL_FILTER;
			queryUri = MediaStore.Video.Media.INTERNAL_CONTENT_URI;
		}else{
			
			return RESULT_PARAMETER_ERROR;
		}

        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(queryUri, null,
                null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);


            if(cursor == null){
                Log.w(TAG, "query music result Cursor == null");
                return RESULT_INTERNAL_ERROR;
            }

            int fileNum = cursor.getCount();
            cursor.moveToFirst();
            infoList.clear();
            for(int counter = 0; counter < fileNum; counter++){
                String path = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
                if(!path.contains(pathFilter)){
                	cursor.moveToNext();
                	continue;
                }

                VideoInfo info = new VideoInfo();
                info.setId(cursor.getString(cursor.getColumnIndex(BaseColumns._ID)));
                info.setTitle(cursor.getString(cursor.getColumnIndex(MediaColumns.TITLE)));
                info.setArtist(cursor.getString(cursor.getColumnIndex(VideoColumns.ARTIST)));
                info.setAlbum(cursor.getString(cursor.getColumnIndex(VideoColumns.ALBUM)));
                info.setDuration(cursor.getString(cursor.getColumnIndex(VideoColumns.DURATION)));
                info.setPath(cursor.getString(cursor.getColumnIndex(MediaColumns.DATA)));
                info.setSize(cursor.getString(cursor.getColumnIndex(MediaColumns.SIZE)));
                infoList.add(info);
                
                
                Result_count++;
                cursor.moveToNext();
            }
        cursor.close();
        return Result_count;
    }
	
	public static int getImageInfoImageNums(Context context,int sourceType){
		String pathFilter = " ";
		Uri queryUri;
		int Result_count = 0;

		if( PARAMETER_SOURCE_TYPE_SD == sourceType){
			
			if(!storageExist(SD_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = SD_FILTER;
			queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_USB == sourceType){
			
			if(!storageExist(USB_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = USB_FILTER;
			queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_INTERNAL == sourceType){
			
			if(!storageExist(INTERNAL_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = INTERNAL_FILTER;
			queryUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
		}else{
			
			return RESULT_PARAMETER_ERROR;
		}

        ContentResolver contentResolver = context.getContentResolver();
        
        if(contentResolver == null){
        	Log.w("contentResolver", sourceType+" :RESULT_INFO_Resolver_NULL");
        	return RESULT_INFO_Resolver_NULL;
        }
        Cursor cursor = contentResolver.query(queryUri, null,
                null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);


        if(cursor == null){
            Log.w(TAG, "query music result Cursor == null");
            return RESULT_INTERNAL_ERROR;
        }

        int fileNum = cursor.getCount();
        Log.d(TAG,"cursor.getCount: "+fileNum);
        Result_count = 0;
        cursor.moveToFirst();
        for(int counter = 0; counter < fileNum; counter++){            	 
            String path = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));                
            if(!path.contains(pathFilter)){
            	cursor.moveToNext();
            	continue;
            }
            Result_count++;
            cursor.moveToNext();
        }
        cursor.close();
        Log.d("getImageInfo", "getImageInfo Result_count :"+Result_count);
        Log.d(TAG, "=====>Result_count3 is:"+Result_count);
        return Result_count;

	}
	
	public static int getImageInfo(Context context,int sourceType,ArrayList<ImageInfo> infoList){
		
		Log.d("getImageInfo", "getImageInfo");
		
		BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		
		String pathFilter = " ";
		Uri queryUri;
		int Result_count = 0;

		if( PARAMETER_SOURCE_TYPE_SD == sourceType){
			
			if(!storageExist(SD_PATH))
				return RESULT_SOURCE_ERROR;
			//pathFilter = SD_PATH;
			pathFilter = SD_FILTER;
			queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_USB == sourceType){
			
			if(!storageExist(USB_PATH))
				return RESULT_SOURCE_ERROR;
			//pathFilter = USB_PATH;
			pathFilter = USB_FILTER;
			queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		}else if( PARAMETER_SOURCE_TYPE_INTERNAL == sourceType){
			
			if(!storageExist(INTERNAL_PATH))
				return RESULT_SOURCE_ERROR;
			pathFilter = INTERNAL_FILTER;
			queryUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
		}else{
			
			return RESULT_PARAMETER_ERROR;
		}

        ContentResolver contentResolver = context.getContentResolver();
        
        if(contentResolver == null){
        	Log.w("contentResolver", sourceType+" :RESULT_INFO_Resolver_NULL");
        	return RESULT_INFO_Resolver_NULL;
        }
        Cursor cursor = contentResolver.query(queryUri, null,
                null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);


            if(cursor == null){
                Log.w(TAG, "query music result Cursor == null");
                return RESULT_INTERNAL_ERROR;
            }

            int fileNum = cursor.getCount();
            Log.d(TAG,"cursor.getCount: "+fileNum);

            cursor.moveToFirst();
            infoList.clear();
            for(int counter = 0; counter < fileNum; counter++){
            
            	//Log.w(TAG, "path is: " + cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
            	 
                String path = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
                /*if(!path.startsWith(pathFilter))
                	continue;*/
                
                if(!path.contains(pathFilter)){
                	cursor.moveToNext();
                	continue;
                }

                ImageInfo info = new ImageInfo();
                info.setId(cursor.getString(cursor.getColumnIndex(BaseColumns._ID)));
                info.setTitle(cursor.getString(cursor.getColumnIndex(MediaColumns.TITLE)));
                info.setPath(cursor.getString(cursor.getColumnIndex(MediaColumns.DATA)));
                info.setSize(cursor.getString(cursor.getColumnIndex(MediaColumns.SIZE)));
                /*Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(contentResolver,cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)),
                		Images.Thumbnails.MICRO_KIND, options);
                if(bitmap == null){
                	
                	Log.w("getImageInfo",info.getTitle()+":Thumbnails == null");
                	
                }
                info.setThumbnail(bitmap);*/
                infoList.add(info);
                Result_count++;
                cursor.moveToNext();
            }
        cursor.close();
        Log.d("getImageInfo", "getImageInfo Result_count :"+Result_count);
        return Result_count;

    }
	
	
	public static String getMusicAlbumImage(Context context,String album_id) {  
        String mUriAlbums = "content://media/external/audio/albums";  
        String[] projection = new String[] { "album_art" };  
        Cursor cur = context.getContentResolver().query(Uri.parse(mUriAlbums + "/" + album_id),  
										                projection, null, null, null);  
       String album_art = null;  
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {  
            cur.moveToNext();  
            album_art = cur.getString(0);  
        }  
        cur.close();  
        cur = null;  
        return album_art;  
    }
	
	
	public static String getVideoAlbumArt(Context context,String album_id) {  
        String mUriAlbums = "content://media/external/video/albums";  
        String[] projection = new String[] { "album_art" };  
        Cursor cur = context.getContentResolver().query(  
                Uri.parse(mUriAlbums + "/" + album_id),  
                projection, null, null, null);  
       String album_art = null;  
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {  
            cur.moveToNext();  
            album_art = cur.getString(0);  
        }  
        cur.close();  
        cur = null;  
        return album_art;  
    }
	
	private static Bitmap mCachedBit = null;
    private static final BitmapFactory.Options sBitmapOptionsCache = new BitmapFactory.Options();
    private static final BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options();
    private static final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
    
    static protected Uri getContentURIForPath(String path) {
        return Uri.fromFile(new File(path));
    }

    private static StringBuilder sFormatBuilder = new StringBuilder();
    private static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
    private static final Object[] sTimeArgs = new Object[5];
    
    
    public static Bitmap getAlbumBitmap(Context context,long songId,long albumId){
    	
    	 Bitmap bm = GetMediasInfo.getArtwork(context, songId, albumId, false);
         if (bm == null) {
             bm = GetMediasInfo.getArtwork(context, songId, -1);
         }
         return bm;
    }
    
   /* public static Bitmap getImageBitmap(Context context,long imageId){
    	
   	 Bitmap bm = GetMediasInfo.getArtwork(context, imageId, albumId, false);
        if (bm == null) {
            bm = GetMediasInfo.getArtwork(context, imageId, -1);
        }
        return bm;
   }*/
    
    private static BitmapFactory.Options options = null;
	
	static{
		
		options = new BitmapFactory.Options();
        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
	}
	
	public static Bitmap getVideoBitmap(Context context,int videoId){
		Bitmap map = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(),videoId,Images.Thumbnails.MICRO_KIND, options);
		if(map == null){
			return BitmapFactory.decodeStream(
	                context.getResources().openRawResource(R.drawable.video_bg), null, options);
		}
		return map;
	}
	
	public static Bitmap getImageBitmap(Context context,int imageId){
		Bitmap map = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(),imageId,Images.Thumbnails.MICRO_KIND, options);
		if(map == null){
			return BitmapFactory.decodeStream(
	                context.getResources().openRawResource(R.drawable.video_bg), null, options);
		}
		return map;
	}

   
    public static Bitmap getArtwork(Context context, long song_id, long album_id) {
        return getArtwork(context, song_id, album_id, true);
    }

    /** Get album art for specified album. You should not pass in the album id
     * for the "unknown" album here (use -1 instead)
     */
    public static Bitmap getArtwork(Context context, long song_id, long album_id,
            boolean allowdefault) {

        if (album_id < 0) {
            // This is something that is not in the database, so get the album art directly
            // from the file.
            if (song_id >= 0) {
                Bitmap bm = getArtworkFromFile(context, song_id, -1);
                if (bm != null) {
                	ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    if (baos.toByteArray().length / 1024 < 50) { 
                        return bm;
                    }
                }
            }
            if (allowdefault) {
                return getDefaultArtwork(context);
            }
            return null;
        }

        ContentResolver res = context.getContentResolver();
        Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
        if (uri != null) {
            InputStream in = null;
            try {
                in = res.openInputStream(uri);
                //return BitmapFactory.decodeStream(in, null, sBitmapOptions);
                return decodeSampledBitmapFromStream(in, 100, 100);
            } catch (FileNotFoundException ex) {
                // The album art thumbnail does not actually exist. Maybe the user deleted it, or
                // maybe it never existed to begin with.
                Bitmap bm = getArtworkFromFile(context, song_id, album_id);
                if (bm != null) {
                    if (bm.getConfig() == null) {
                        bm = bm.copy(Bitmap.Config.RGB_565, false);
                        if (bm == null && allowdefault) {
                            return getDefaultArtwork(context);
                        }
                    }
                } else if (allowdefault) {
                    bm = getDefaultArtwork(context);
                }
                return bm;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                }
            }
        }
        return null;
    }
    
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {   
	    final int height = options.outHeight;   
	    final int width = options.outWidth;   
	    int inSampleSize = 1;   
	    if (height > reqHeight || width > reqWidth) {   
	        final int heightRatio = Math.round((float) height / (float) reqHeight);   
	        final int widthRatio = Math.round((float) width / (float) reqWidth);    
	        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;   
	    }   
	    return inSampleSize;   
	} 
	
	public static Bitmap decodeSampledBitmapFromStream(InputStream res, int reqWidth, int reqHeight) {   
	    BitmapFactory.Options options = new BitmapFactory.Options();   
	    options.inJustDecodeBounds = true; 
	    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);   
	    options.inJustDecodeBounds = false;   
	    return BitmapFactory.decodeStream(res, null, options);   
	}  
   
    private static final String sExternalMediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString();
    private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) {
        Bitmap bm = null;
        byte [] art = null;
        String path = null;

    	BitmapFactory.Options options=new BitmapFactory.Options();  
    	options.inJustDecodeBounds = false;  
    	options.inSampleSize = 20;     
    	//Bitmap btp =BitmapFactory.decodeStream(is,null,options);

        if (albumid < 0 && songid < 0) {
            throw new IllegalArgumentException("Must specify an album or a song id");
        }

        try {
            if (albumid < 0) {
                Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    bm = BitmapFactory.decodeFileDescriptor(fd);
                    BitmapFactory.decodeFileDescriptor(fd, null, options);
                }
            } else {
                Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid);
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
                }
            }
        } catch (IllegalStateException ex) {
        } catch (FileNotFoundException ex) {
        }
        if (bm != null) {
            mCachedBit = bm;
        }
        return bm;
    }
    
    private static Bitmap getDefaultArtwork(Context context) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        return BitmapFactory.decodeStream(
                context.getResources().openRawResource(R.drawable.cd_bg), null, opts);
    }
}

你可能感兴趣的:(Android读取SD/USB空间大小以及内容)