最近项目需要实现Android截屏分享功能,包括Android截屏获取图片、将图片保存到本地、通知系统相册更新、通过微信、QQ、微博分享截屏图片,本篇博客作为总结回顾。
public Bitmap shotScreen(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(false);
view.destroyDrawingCache();
return bitmap;
}
public Bitmap shotActivityNoBar(Activity activity) {
// 获取windows中最顶层的view
View view = activity.getWindow().getDecorView();
view.buildDrawingCache();
// 获取状态栏高度
Rect rect = new Rect();
view.getWindowVisibleDisplayFrame(rect);
int statusBarHeights = rect.top;
Display display = activity.getWindowManager().getDefaultDisplay();
// 获取屏幕宽和高
int widths = display.getWidth();
int heights = display.getHeight();
// 允许当前窗口保存缓存信息
view.setDrawingCacheEnabled(true);
// 去掉状态栏
Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
statusBarHeights, widths, heights - statusBarHeights);
// 销毁缓存信息
view.destroyDrawingCache();
return bmp;
}
public Bitmap getFragmentBitmap(Fragment fragment) {
View v = fragment.getView();
v.buildDrawingCache(false);
return v.getDrawingCache();
}
绘制View的方式只适用于静态View,SurfaceView、IjkVideoView等播放视频的View,不能截取到;此外,某些动画类View也不能截取到。针对上述情况,可获取SurfaceView的一帧生成bitmap,将bitmap进行合并,同理动画类View也可以合并。例如,最底层播放视频、中间层播放动画、最上层是普通的view,可将bitmap合并,如下:
public Bitmap combineBitmapInCenter(Bitmap background, Bitmap midBitmap, Bitmap foreground) {
if (!background.isMutable()) {
background = background.copy(Bitmap.Config.ARGB_8888, true);
}
Paint paint = new Paint();
Canvas canvas = new Canvas(background);
int bw = background.getWidth();
int bh = background.getHeight();
int mw = midBitmap.getWidth();
int mh = midBitmap.getHeight();
int mx = (mw - bw) / 2;
int my = (mh - bh) / 2;
canvas.drawBitmap(midBitmap, mx, my, paint);
int fw = foreground.getWidth();
int fh = foreground.getHeight();
int fx = (fw - bw) / 2;
int fy = (fh - bh) / 2;
canvas.drawBitmap(foreground, fx, fy, paint);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return background;
}
需要注意:view的绘制必须在UI线程完成,否则会crash;bitmap的合并会较耗时,需在子线程完成。
public void saveBitmapToFile(String fileName, Bitmap bitmap) {
if (TextUtils.isEmpty(fileName) || bitmap == null) return;
try {
File f = new File(fileName);
f.createNewFile();
FileOutputStream fOut = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
Log.i("ScreenShotUtil", "保存失败");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void AlbumScan(String fileName) {
MediaScannerConnection.scanFile(mActivity.getApplicationContext(), new String[]{fileName}, new String[]{"image/jpeg"}, null);
}
public void shareToWexinCircle() {
if (iShareService.isWeixinInstalled()) {//判断微信是否安装
Bitmap mWXShareBitmap = mLatesBitmap;//将截屏得到的bitmap赋值
WXImageObject imgObject = new WXImageObject(mWXShareBitmap);
WXMediaMessage mediaMessage = new WXMediaMessage();
mediaMessage.mediaObject = imgObject;
Log.i(TAG,"mediaMessage.mediaObject = imgObject");
//设置缩略图
Bitmap thumbBmp = Bitmap.createScaledBitmap(mWXShareBitmap,50,80,true);
mediaMessage.thumbData = bmpToByteArray(thumbBmp,true);
Log.i(TAG,"设置缩略图");
//request to wx
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("img");//分享类型是图片
req.message = mediaMessage;
req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈
Log.i(TAG,"request to wx");
IWXAPI api = WXAPIFactory.createWXAPI(mActivity,"微信分享id",true);
api.registerApp("微信分享id");
boolean result = api.sendReq(req);
Log.i(TAG,"share to circle:"+result);
} else {
ToastUtils.show(mActivity, "您没有安装微信客户端");
}
}
public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
public void shareWexinFriend() {
if (iShareService.isWeixinInstalled()) {
mWXShareBitmap = mLatesBitmap;
WXImageObject imgObject = new WXImageObject(mWXShareBitmap);
WXMediaMessage mediaMessage = new WXMediaMessage();
mediaMessage.mediaObject = imgObject;
//设置缩略图
Bitmap thumbBmp = Bitmap.createScaledBitmap(mWXShareBitmap,50,80,true);
mediaMessage.thumbData = bmpToByteArray(thumbBmp,true);
//request to wx
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction =buildTransaction("img");
req.message = mediaMessage;
req.scene = SendMessageToWX.Req.WXSceneSession;
IWXAPI api = WXAPIFactory.createWXAPI(mActivity,"微信分享id",true);
api.registerApp("微信分享id");
boolean result = api.sendReq(req);
Log.i(TAG,"share to weixin:"+result );
} else {
ToastUtils.show(mActivity, "您没有安装微信客户端");
}
}
public void shareToQQFriend() {
if (iShareService.isQQInstalled()) {//判断QQ是否安装
Tencent tencent = Tencent.createInstance("qq id", mActivity);
Bundle params = new Bundle();
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, mLatestImagePath);//QQ分享只能分享本地图片,传入本地图片路径
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
tencent.shareToQQ(mActivity, params, new IUiListener() {//分享后的回调
@Override
public void onComplete(Object o) {
ToastUtils.show(mActivity,"分享成功!");
}
@Override
public void onError(UiError uiError) {
ToastUtils.show(mActivity,"分享失败,稍后重试!");
Log.i(TAG,"shareToQQ onError");
}
@Override
public void onCancel() {
Log.i(TAG,"shareToQQ onCancel");
}
});
} else {
ToastUtils.show(mActivity, "您没有安装QQ客户端");
}
}
public void shareToQQZone() {
if (iShareService.isQQInstalled()) {
Tencent tencent = Tencent.createInstance("QQ id", mActivity);
Bundle params = new Bundle();
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, mLatestImagePath);
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
tencent.shareToQQ(mActivity, params, new IUiListener() {
@Override
public void onComplete(Object o) {
ToastUtils.show(mActivity,"分享成功!");
}
@Override
public void onError(UiError uiError) {
ToastUtils.show(mActivity,"分享失败,请稍后重试!");
Log.i(TAG,"shareToQQ onError,error code:"+uiError.errorCode);
}
@Override
public void onCancel() {
Log.i(TAG,"shareToQQ onCancel");
}
});
} else {
ToastUtils.show(mActivity, "您没有安装QQ客户端");
}
}
public void shareToWeibo() {
if (iShareService.isWeiboInstalled()) {
Log.i(TAG,"iShareService.isWeiboInstalled()");
IWeiboShareAPI api = WeiboShareSDK.createWeiboAPI(mActivity, "微博id");
if(api.isWeiboAppInstalled()) {
api.registerApp();
}
WeiboMultiMessage weiboMultiMessage = new WeiboMultiMessage();
Bitmap bitmap = mLatesBitmap;//截图bitmap
ImageObject imageObject = new ImageObject();
imageObject.setImageObject(bitmap);
weiboMultiMessage.imageObject = imageObject;
SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
request.transaction = String.valueOf(System.currentTimeMillis());
request.multiMessage = weiboMultiMessage;
boolean requestWeibo = api.sendRequest(request);
Log.i(TAG,"share to weibo:"+requestWeibo );
} else {
ToastUtils.show(mActivity, "您没有安装微博客户端");
}
}
具体参考微信、QQ、微博的官方文档及分享SDK。