多数人都用过 ThumbnailUtils.createVideoThumbnail() 方法,该方法在 2.x 系统下可用,API Level > 14 时却只能返回 null,以下为解决该问题方案:
重写 createVideoThumbnail() 方法,如下
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Bitmap createVideoThumbnail(String url, int width, int height) {
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
int kind = MediaStore.Video.Thumbnails.MINI_KIND;
try {
if (Build.VERSION.SDK_INT >= 14) {
retriever.setDataSource(url, new HashMap());
} else {
retriever.setDataSource(url);
}
bitmap = retriever.getFrameAtTime();
} catch (IllegalArgumentException ex) {
// Assume this is a corrupt video file
} catch (RuntimeException ex) {
// Assume this is a corrupt video file.
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
// Ignore failures while cleaning up.
}
}
if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
}
return bitmap;
}
调用该方法并给 ImageView 设置
String urlVideo="http://mvvideo2.meitudata.com/5785a7e3e6a1b824.mp4";
ImageView iv_test = (ImageView) findViewById(R.id.iv_test);
iv_test.setImageBitmap(createVideoThumbnail(urlVideo,200,200));