Files
assistant-android/app/src/main/java/com/gh/common/util/ShareUtils.java
2016-12-06 17:06:00 +08:00

495 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.ClipboardManager;
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.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
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.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.gh.gamecenter.R;
import com.gh.gamecenter.WeiBoShareActivity;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
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.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
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.util.ArrayList;
import java.util.List;
/**
* Created by khy on 2016/9/4.
*/
public class ShareUtils {
private static ShareUtils instance;
private String shareUrl;
private String shareGameName;
private String shareIcon;
private String shareNewsTitle; // shareNewsTitle不为空就是新闻分享否则是游戏分享
private boolean isPlugin = false;
private static IWXAPI api;
private static Tencent mTencent;
private Handler handler;
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_sinaweibo_logo, R.drawable.share_shortmessage_logo
, R.drawable.share_copyfont_logo, R.drawable.share_cancel_logo};
private String[] arrLabel = {"微信好友", "朋友圈", "QQ好友", "QQ空间", "新浪微博", "短信", "复制链接", "取消"};
private PopupWindow popupWindow;
private Context context;
public static ShareUtils getInstance(Context context) {
if (instance == null) {
instance = new ShareUtils();
mTencent = Tencent.createInstance("1104659243", context); //初始化QQ分享
api = WXAPIFactory.createWXAPI(context, "wx3ffd0785fad18396"); //初始化微信分享
}
instance.context = context;
return instance;
}
public void showShareWindows(View view, String url, String gameName, String icon ,String newsTitle, boolean isPlugin){
this.shareIcon = icon;
this.shareGameName = gameName;
this.shareUrl = url;
this.shareNewsTitle = newsTitle;
this.isPlugin = isPlugin;
RelativeLayout contentView = new RelativeLayout(context);
contentView.setBackgroundColor(0x8c000000);
contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
RecyclerView shareRecyclerView = new RecyclerView(context);
shareRecyclerView.setPadding(DisplayUtils.dip2px(context, 20), DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 20), 0);
shareRecyclerView.setBackgroundColor(Color.WHITE);
//RecyclerView禁止滑动
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 4){
@Override
public boolean canScrollVertically() {
return false;
}
};
shareRecyclerView.setLayoutManager(gridLayoutManager);
shareRecyclerView.setAdapter(new ShareRecyclerViewAdapter());
RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
, DisplayUtils.dip2px(context, 200));
rlParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
contentView.addView(shareRecyclerView,rlParams);
popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
, LinearLayout.LayoutParams.MATCH_PARENT, true);
popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
contentView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0 && popupWindow != null
&& popupWindow.isShowing()) {
popupWindow.dismiss();
}
return false;
}
});
}
private class ShareRecyclerViewAdapter extends RecyclerView.Adapter<ShareRecyclerViewAdapter.ViewHolder>{
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DisplayUtils.dip2px(context, 90)));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
linearLayout.setBackgroundResource(R.drawable.cardview_item_style);
ImageView shareLogo = new ImageView(context);
LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(context, 45), DisplayUtils.dip2px(context, 45));
logoParams.setMargins(0, DisplayUtils.dip2px(context, 10), 0, 0);
shareLogo.setLayoutParams(logoParams);
TextView shareLabel = new TextView(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, DisplayUtils.dip2px(context,10), 0, 0);
shareLabel.setLayoutParams(layoutParams);
shareLabel.setGravity(Gravity.CENTER);
shareLabel.setTextColor(Color.parseColor("#3a3a3a"));
shareLabel.setTextSize(13);
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(arrLabel[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (holder.getPosition()){
case 0:
wechatSahre();
break;
case 1:
wechatMomentsSahre();
break;
case 2:
qqSahre();
break;
case 3:
qZoneSahre();
break;
case 4:
sinaWeiboSahre();
break;
case 5:
shortMessageSahre();
break;
case 6:
copyLink(shareUrl);
break;
case 7:
popupWindow.dismiss();
break;
}
}
});
}
@Override
public int getItemCount() {
return 8;
}
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);
}
}
}
//QQ分享
private void qqSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
if (shareNewsTitle != null){
params.putString(QQShare.SHARE_TO_QQ_TITLE, shareNewsTitle);
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "来自光环助手(最强卡牌神器)");
}else {
params.putString(QQShare.SHARE_TO_QQ_TITLE, "向你推荐:");
if (isPlugin){
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareGameName + "(光环加速版)");
}else {
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareGameName);
}
}
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareIcon);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "光环助手");
mTencent.shareToQQ(
(Activity) context, params,QqShareListener);
popupWindow.dismiss();
}
//微信好友分享
private void wechatSahre(){
Utils.toast(context,"分享跳转中...");
WXWebpageObject webpage = new WXWebpageObject();
WXMediaMessage msg = new WXMediaMessage(webpage);
webpage.webpageUrl = shareUrl;
if (shareNewsTitle != null){
msg.title = shareNewsTitle;
msg.description = "来自光环助手(最强卡牌神器)";
}else {
if (isPlugin){
msg.title = "向你推荐";
msg.description = shareGameName + "(光环加速版)";
}else {
msg.title = "向你推荐";
msg.description = shareGameName;
}
}
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneSession;
loadBitMap(shareIcon, msg, req);
popupWindow.dismiss();
}
//QQ空间分享
private void qZoneSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
if (shareNewsTitle != null){
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareNewsTitle);
}else {
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "向你推荐:");
if (isPlugin){
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareGameName + "(光环加速版)");
}else {
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareGameName);
}
}
ArrayList<String> imageUrls = new ArrayList<String>();
imageUrls.add(shareIcon);
params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_NO_TYPE);
params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "光环助手");
mTencent.shareToQzone(
(Activity) context, params,QqShareListener);
popupWindow.dismiss();
}
//微信朋友圈分享
private void wechatMomentsSahre(){
Utils.toast(context,"分享跳转中...");
WXWebpageObject webpage = new WXWebpageObject();
WXMediaMessage msg = new WXMediaMessage(webpage);
webpage.webpageUrl = shareUrl;
if (shareNewsTitle != null){
msg.title = shareNewsTitle;
}else {
if (isPlugin){
msg.title = "向你推荐:" + shareGameName + "(光环加速版)";
}else {
msg.title = "向你推荐:" + shareGameName;
}
}
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneTimeline;
loadBitMap(shareIcon, msg, req);
popupWindow.dismiss();
}
//新浪微博分享
private void sinaWeiboSahre(){
Intent intent = new Intent(context, WeiBoShareActivity.class);
Bundle bundle = new Bundle();
bundle.putString("shareNewsTitle", shareNewsTitle);
bundle.putString("shareIcon", shareIcon);
bundle.putString("shareGameName", shareGameName);
bundle.putString("shareUrl", shareUrl);
bundle.putBoolean("isPlugin",isPlugin);
intent.putExtras(bundle);
context.startActivity(intent);
popupWindow.dismiss();
}
//短信分享
private void shortMessageSahre(){
String smsBody;
if (shareNewsTitle != null){
smsBody = shareNewsTitle + shareUrl;
}else {
if (isPlugin){
smsBody = "向你推荐:" + shareGameName + "(光环加速版)" + shareUrl;
}else {
smsBody = "向你推荐:" + shareGameName + shareUrl;
}
}
Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( "smsto:" ));
sendIntent.putExtra( "sms_body", smsBody);
sendIntent.setType( "vnd.android-dir/mms-sms" );
try {
context.startActivity(sendIntent);
} catch (Exception e) {
Utils.toast(context, "系统异常,分享失败");
e.printStackTrace();
}
popupWindow.dismiss();
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
//复制文字链接
private void copyLink(String copyContent) {
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(copyContent);
popupWindow.dismiss();
Utils.toast(context,"复制成功");
}
private void loadBitMap(final String iconUrl, final WXMediaMessage msg, final SendMessageToWX.Req req){
ImageUtils.getInstance().display(context, iconUrl, new BaseBitmapDataSubscriber() {
@Override
protected void onNewResultImpl(Bitmap bitmap) {
Bitmap compressBp = compressBitmap(bitmap);
Bitmap resultBp = addBackGround(compressBp);
msg.thumbData = Util.bmpToByteArray(resultBp, true);
api.sendReq(req);
}
@Override
protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
Utils.log("分享获取bitmap失败");
}
});
}
//添加背景防止图片格式为PNG的图片分享出现黑框问题
public Bitmap addBackGround(Bitmap result) {
Bitmap bgBitmap;
int[] colors = new int[result.getWidth()*result.getHeight()];
for (int i = 0; i < colors.length; i++) {
colors[i] = Color.WHITE;
}
bgBitmap = Bitmap.createBitmap(colors, result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap newmap = Bitmap
.createBitmap(result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newmap);
canvas.drawBitmap(bgBitmap, 0, 0, null);
canvas.drawBitmap(result, (result.getHeight() - result.getWidth()) / 2,
(result.getHeight() - result.getWidth()) / 2, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newmap;
}
//压缩图片
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;
}
//QQ或者QQ空间分享回调处理
public IUiListener QqShareListener = new IUiListener() {
@Override
public void onComplete(Object o) {
Utils.toast(context, "分享成功");
}
@Override
public void onError(UiError uiError) {
Utils.toast(context, "分享失败");
}
@Override
public void onCancel() {
Utils.toast(context, "分享已取消");
}
};
//检查是否安装手机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 (pn.equals("com.tencent.mobileqq")) {
return true;
}
}
}
return false;
}
}