Files
assistant-android/app/src/main/java/com/gh/common/util/MessageShareUtils.java
2018-02-03 10:16:27 +08:00

480 lines
18 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.gh.common.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.support.v4.content.*;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gh.common.constant.Config;
import com.gh.gamecenter.R;
import com.lightgame.utils.Utils;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.platformtools.Util;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* Created by khy on 2016/11/8.
*/
public class MessageShareUtils {
private static MessageShareUtils instance;
private IWXAPI mIWXAPI;
private Tencent mTencent;
private Bitmap shareBm; //分享截图
private String picName;
private boolean isPlugin = false;
private int[] arrLogo = {
R.drawable.share_wechat_logo,
R.drawable.share_wechatmoments_logo,
R.drawable.share_qq_logo,
R.drawable.share_qzone_logo,
R.drawable.share_save
};
private String[] mArrLabel = {"微信好友", "朋友圈", "QQ好友", "QQ空间", "保存"};
private PopupWindow mPopupWindow;
private Context mContext;
//TODO 干掉activity将context变成applicationcontext
private Activity mActivity; // 用来关闭分享页面
//QQ或者QQ空间分享回调处理
public IUiListener QqShareListener = new IUiListener() {
@Override
public void onComplete(Object o) {
Utils.toast(mContext, "分享成功");
}
@Override
public void onError(UiError uiError) {
Utils.toast(mContext, "分享失败");
}
@Override
public void onCancel() {
Utils.toast(mContext, R.string.share_cancel_hint);
}
};
// 适配快传成绩单分享
private int contentSize;
private int paddTop;
private int picSize;
private int itemSize;
private int gridCount;
private int marImg;
private int shareType;
private MessageShareUtils(Context context) {
mTencent = Tencent.createInstance(Config.TENCENT_APPID, context); //初始化QQ分享
mIWXAPI = WXAPIFactory.createWXAPI(context, Config.WECHAT_APPID); //初始化微信分享
//TODO changed to application context
mContext = context;
}
public static MessageShareUtils getInstance(Context context) {
if (instance == null) {
instance = new MessageShareUtils(context);
}
return instance;
}
//检查是否安装手机QQ
public static boolean isQQClientAvailable(Context context) {
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName;
if ("com.tencent.mobileqq".equals(pn)) {
return true;
}
}
}
return false;
}
public IWXAPI getIWXAPI() {
return mIWXAPI;
}
public Tencent getTencent() {
return mTencent;
}
public void showShareWindows(Activity activity, View view, Bitmap bitmap, String picName, int shareType) {
this.shareBm = bitmap;
this.picName = picName;
this.shareType = shareType;
this.mActivity = activity;
if (shareType == 2) {
contentSize = 75;
paddTop = 0;
gridCount = 4;
picSize = 30;
itemSize = 75;
marImg = 10;
} else {
contentSize = 100;
paddTop = 10;
gridCount = 5;
picSize = 43;
itemSize = 90;
marImg = 13;
}
RelativeLayout contentView = new RelativeLayout(mContext);
contentView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
contentView.setBackgroundColor(0x8c000000);
contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
RecyclerView shareRecyclerView = new RecyclerView(mContext);
shareRecyclerView.setPadding(DisplayUtils.dip2px(mContext, 10), DisplayUtils.dip2px(mContext, paddTop), DisplayUtils.dip2px(mContext, 10), 0);
shareRecyclerView.setBackgroundColor(Color.WHITE);
//RecyclerView禁止滑动
GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, gridCount) {
@Override
public boolean canScrollVertically() {
return false;
}
};
shareRecyclerView.setLayoutManager(gridLayoutManager);
shareRecyclerView.setAdapter(new ShareRecyclerViewAdapter());
if (shareType == 0 || shareType == 2) {
LinearLayout llBottom = (LinearLayout) view;
ViewGroup.LayoutParams layoutParams = llBottom.getLayoutParams();
layoutParams.height = DisplayUtils.dip2px(mContext, contentSize);
shareRecyclerView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
llBottom.addView(shareRecyclerView);
return;
}
RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
, DisplayUtils.dip2px(mContext, 106));
rlParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
contentView.addView(shareRecyclerView, rlParams);
mPopupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
, LinearLayout.LayoutParams.MATCH_PARENT, true);
mPopupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPopupWindow.dismiss();
}
});
contentView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0 && mPopupWindow != null
&& mPopupWindow.isShowing()) {
mPopupWindow.dismiss();
}
return false;
}
});
}
//QQ分享
private void qqSahre() {
Utils.toast(mContext, "分享跳转中...");
Bundle params = new Bundle();
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, mContext.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, mContext.getString(R.string.app_name));
params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,
QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
mTencent.shareToQQ(
mActivity, params, QqShareListener);
if (mPopupWindow == null) return;
mPopupWindow.dismiss();
}
//QQ空间分享
private void qZoneSahre() {
Utils.toast(mContext, "分享跳转中...");
Bundle params = new Bundle();
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, mContext.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, mContext.getString(R.string.app_name));
params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,
QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
mTencent.shareToQQ(
mActivity, params, QqShareListener);
if (mPopupWindow == null) return;
mPopupWindow.dismiss();
}
//微信好友分享
private void wechatSahre() {
Utils.toast(mContext, "分享跳转中...");
//官方分享
// WXImageObject imgObj = new WXImageObject();
// imgObj.setImagePath(mContext.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
// WXMediaMessage msg = new WXMediaMessage();
// msg.mediaObject = imgObj;
//
// SendMessageToWX.Req req = new SendMessageToWX.Req();
// req.transaction = buildTransaction("img");
// req.message = msg;
// req.scene = SendMessageToWX.Req.WXSceneSession;
//
// Bitmap compressBp = compressBitmap(shareBm);
// msg.thumbData = Util.bmpToByteArray(compressBp, true);
// mIWXAPI.sendReq(req);
//调用手机系统分享
try {
mContext.startActivity(IntentUtils.getWechatShareIntent(mContext, picName));
} catch (Exception e) {
Utils.toast(mContext, "分享失败!请检查是否已安装微信");
e.printStackTrace();
}
if (mPopupWindow == null) return;
mPopupWindow.dismiss();
}
//微信朋友圈分享
private void wechatMomentsSahre() {
Utils.toast(mContext, "分享跳转中...");
WXImageObject imgObj = new WXImageObject();
imgObj.setImagePath(mContext.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = imgObj;
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("img");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneTimeline;
Bitmap compressBp = compressBitmap(shareBm);
msg.thumbData = Util.bmpToByteArray(compressBp, true);
mIWXAPI.sendReq(req);
if (mPopupWindow == null) return;
mPopupWindow.dismiss();
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
//压缩图片
private Bitmap compressBitmap(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
float zoom = (float) Math.sqrt(10 * 1024 / (float) bos.toByteArray().length);
Matrix matrix = new Matrix();
matrix.setScale(zoom, zoom);
Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
while (bos.toByteArray().length > 10 * 1024) {
System.out.println(bos.toByteArray().length);
matrix.setScale(0.9f, 0.9f);
result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
}
return result;
}
//写到存储卡中
public void writeBitmap(String path, String name, Bitmap bitmap, boolean isToast) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
File _file = new File(path, name);
if (_file.exists()) {
_file.delete();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(_file);
if (name != null && !"".equals(name)) {
int index = name.lastIndexOf(".");
if (index != -1 && (index + 1) < name.length()) {
String extension = name.substring(index + 1).toLowerCase();
if ("png".equals(extension)) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} else if ("jpg".equals(extension)
|| "jpeg".equals(extension)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
}
if (isToast) {
Utils.toast(mContext, "成功保存到相册");
//刷新手机图片库
refreshImage(_file, mContext);
}
}
}
} catch (FileNotFoundException e) {
Utils.log("消息分享异常" + e.toString());
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void refreshImage(File _file, Context context) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(_file);
intent.setData(uri);
context.sendBroadcast(intent);
Utils.log("保存分享图片路径:" + _file.getAbsolutePath());
}
class ShareRecyclerViewAdapter extends RecyclerView.Adapter<ShareRecyclerViewAdapter.ViewHolder> {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(mContext);
linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtils.dip2px(mContext, itemSize)));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
linearLayout.setBackgroundResource(R.drawable.cardview_item_style);
ImageView shareLogo = new ImageView(mContext);
LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(mContext, picSize), DisplayUtils.dip2px(mContext, picSize));
logoParams.setMargins(0, DisplayUtils.dip2px(mContext, 10), 0, 0);
shareLogo.setLayoutParams(logoParams);
TextView shareLabel = new TextView(mContext);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, DisplayUtils.dip2px(mContext, 10), 0, 0);
shareLabel.setLayoutParams(layoutParams);
shareLabel.setGravity(Gravity.CENTER);
shareLabel.setTextColor(ContextCompat.getColor(mContext, R.color.text_3a3a3a));
shareLabel.setTextSize(marImg);
linearLayout.addView(shareLogo);
linearLayout.addView(shareLabel);
return new ViewHolder(linearLayout);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.shareLogo.setImageResource(arrLogo[position]);
holder.shareLabel.setText(mArrLabel[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (holder.getPosition()) {
case 0:
wechatSahre();
if (shareType != 2) {
// activity.finish();
}
break;
case 1:
wechatMomentsSahre();
if (shareType != 2) {
// activity.finish();
}
break;
case 2:
qqSahre();
break;
case 3:
qZoneSahre();
break;
case 4:
String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/ghzhushou/";
writeBitmap(savePath, "gh-" + new Date().getTime() + ".jpg", shareBm, true);
if (mPopupWindow == null) return;
mPopupWindow.dismiss();
// activity.finish();
break;
}
}
});
}
@Override
public int getItemCount() {
return gridCount;
}
public class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout linearLayout;
TextView shareLabel;
ImageView shareLogo;
public ViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView;
shareLogo = (ImageView) linearLayout.getChildAt(0);
shareLabel = (TextView) linearLayout.getChildAt(1);
}
}
}
}