Java - Android集成社会化分享组件
组件暂支持: 微信,QQ,围脖,复制粘贴
集成微信相关的分享
-
按照官方文档,集成sdk
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
-
按照官方文档,集成sdk
-
项目模块下配置manifest.xml文件
<application> .... <!--这里使用对话框模式,为了方便把所有的应用回调集中到一起--> <android:name=".wxapi.WXEntryActivity" android:configChanges="keyboardHidden|orientation" android:exported="true" android:label="@string/app_name" android:launchMode="singleTask" android:screenOrientation="portrait" android:theme="@style/ActionSheetDialogActivityTheme" /> .... </application>
-
添加wxEntryActivity.java类
//暂时补贴出代码,请看后面有彩蛋!
-
-
如何编写分享辅助类?使用单例类
下面我们写一些常用方法
public class WechatShareManager { private static WechatShareManager wechatShareManager; public static WechatShareManager getInstance(Context context) { if (wechatShareManager == null) { synchronized (WechatShareManager.class) { wechatShareManager = new WechatShareManager(context); } } return wechatShareManager; } private Context context; private IWXAPI wxapi; /** * 构造函数 * @param context 上下文对象 **/ private WechatShareManager(Context context) { this.context = context; wxapi = WXAPIFactory.createWXAPI(context, BuildConfig.WechatApiKey, true); wxapi.registerApp(BuildConfig.WechatApiKey); } /** * 分享文本到微信 * * @param shareToWhere 分享到哪里 * @param shareText 文本内容 */ public void shareTextToWechat(int shareToWhere, String shareText) { WXTextObject textObject = new WXTextObject(shareText); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.message = new WXMediaMessage(textObject); req.transaction = buildTransaction("text"); req.scene = shareToWhere == 0 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; wxapi.sendReq(req); } /** * 分享图片到微信 * * @param shareToWhere 分享到微信哪里 * @param imgUrl 图片内容 */ public void shareImageToWechat(final int shareToWhere, String imgUrl) { new ImageDownloader(context, imgUrl, new ImageDownloader.OnDownloadListener() { @Override public void onStart() { } @Override public void onDownloading(int total, int progress) { } @Override public void onCompleted(final boolean isSuccessful, final Object result) { ((Activity)context).runOnUiThread(new Runnable() { @Override public void run() { if(isSuccessful){ byte[] picData = (byte[])result; WXImageObject imgObj = new WXImageObject(BitmapFactory.decodeByteArray(picData, 0, picData.length)); WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = imgObj; msg.thumbData = picData; SendMessageToWX.Req req = new SendMessageToWX.Req(); req.message = msg; req.transaction = buildTransaction("img"); req.scene = shareToWhere == 0 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; wxapi.sendReq(req); }else{ Toast.makeText(context.getApplicationContext(), "获取分享资源异常", Toast.LENGTH_SHORT).show(); ((Activity)context).finish(); } } }); } }).start(); } /** * 分享图文信息到微信 * * @param shareToWhere 分享到哪里去, 0 - 微信朋友圈, 其他 - 微信朋友 * @param title 标题 * @param description 描述 * @param shareUrl 分享的URL链接 * @param imgUrl 图片内容 */ public void shareTeletextMessageToWechat(final int shareToWhere, final String title, final String description, final String shareUrl, final String imgUrl) { new ImageDownloader(context, imgUrl, new ImageDownloader.OnDownloadListener() { @Override public void onStart() { } @Override public void onDownloading(int total, int progress) { } @Override public void onCompleted(final boolean isSuccessful, final Object result) { ((Activity)context).runOnUiThread(new Runnable() { @Override public void run() { if(isSuccessful){ WXWebpageObject webpage = new WXWebpageObject(); webpage.webpageUrl = shareUrl; byte[] picData = (byte[])result; WXImageObject imgObj = new WXImageObject(BitmapFactory.decodeByteArray(picData, 0, picData.length)); WXMediaMessage msg = new WXMediaMessage(webpage); msg.title = title; msg.description = description; msg.thumbData = (byte[])result; SendMessageToWX.Req req = new SendMessageToWX.Req(); req.message = msg; req.transaction = buildTransaction("img"); req.scene = shareToWhere == 0 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; wxapi.sendReq(req); }else{ Toast.makeText(context.getApplicationContext(), "获取分享资源异常", Toast.LENGTH_SHORT).show(); ((Activity)context).finish(); } } }); } }).start(); } /** * 结果数据回调 * @param intent * @param callback * @return */ public WechatShareManager doResultIntent(Intent intent, IWXAPIEventHandler callback){ if(wxapi != null) wxapi.handleIntent(intent, callback); return this; } private String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); } }
集成QQ相关的分享
-
配置SDK
-
添加依赖
//腾讯QQSDK compile files('libs/mta-sdk-1.6.2.jar') compile files('libs/open_sdk_r5788.jar')
-
manifest.xml配置activity,注意添加TencentApiKey
<application> <activity android:name="com.tencent.tauth.AuthActivity" android:noHistory="true" android:launchMode="singleTask" > <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="tencent${TencentApiKey}" /> </intent-filter> </activity> <activity android:name="com.tencent.connect.common.AssistActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:configChanges="orientation|keyboardHidden|screenSize" /> </application>
-
-
实现QQ分享代码
public class TencentShareManager { private static TencentShareManager tencentShareManager; public static TencentShareManager getInstance(Context context){ if(tencentShareManager == null){ synchronized (TencentShareManager.class){ tencentShareManager = new TencentShareManager(context); } } return tencentShareManager; } private Tencent tencent; private TencentShareManager(Context context) { tencent = Tencent.createInstance(BuildConfig.TencentApiKey, context.getApplicationContext()); } /** * 分享图文消息到QQ * * @param activity 上下文对象 * @param shareToWhere 取值:{@link QQShare#SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN} & {@link QQShare#SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE} * @param appName APP名称 * @param title 标题名称 * @param description 内容描述 * @param shareUrl 分享的URL * @param imgUrl 图片地址 * @param callback 结果回调 */ public void shareTeletextMessageToQQ(Activity activity, int shareToWhere, String appName, String title, String description, String shareUrl, String imgUrl, IUiListener callback) { final Bundle params = new Bundle(); params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT); params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl); params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl); params.putString(QQShare.SHARE_TO_QQ_APP_NAME, appName); params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, shareToWhere); tencent.shareToQQ(activity, params, callback); } /** * 分享纯图 * * @param activity 上下文对象 * @param appName 应用名称 * @param imgPath 图片本地路径 * @param callback 结果回调 */ public void shareImageToQQ(Activity activity, String appName, String imgPath, IUiListener callback) { Bundle params = new Bundle(); params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imgPath); params.putString(QQShare.SHARE_TO_QQ_APP_NAME, appName); 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(activity, params, callback); } /** * 分享图文到QQ空间 * @param activity 上下文对象 * @param title 标题 * @param description 内容描述 * @param shareUrl 分享的链接 * @param imgUrls 图片链接集合 * @param callback 结果回调 */ public void shareToQzone(Activity activity, String title, String description, String shareUrl, ArrayList<String> imgUrls, IUiListener callback) { Bundle params = new Bundle(); params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT); params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);//必填 params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, description);//选填 params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareUrl);//必填 if(imgUrls != null && imgUrls.size() > 0) params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgUrls); tencent.shareToQzone(activity, params, callback); } /** * 应用调用Andriod_SDK接口时,如果要成功接收到回调,需要在调用接口的Activity的onActivityResult方法中增加如下代码: * * @param requestCode * @param resultCode * @param data * @param listener */ public void onActivityResult(int requestCode, int resultCode, Intent data, IUiListener listener) { Tencent.onActivityResultData(requestCode, resultCode, data, listener); } }
PS: 备注,结果回调请一定在Activity中使用onActivityResult,请稍后查看最后的彩蛋WxEntryActivity.java
集成新浪微博的分享
-
集成新浪SDK
-
配置根目录的build.gradle,添加以下groovy代码
buildscript { ... repositories { jcenter() mavenCentral() maven { url "https://dl.bintray.com/thelasterstar/maven/" } ... } } allprojects { repositories { jcenter() mavenCentral() maven { url "https://dl.bintray.com/thelasterstar/maven/" } } }
-
配置所在模块的build.gradle文件
//新浪微博SDK compile 'com.sina.weibo.sdk:core:2.0.3:openDefaultRelease@aar'
-
-
实现微博分享的代码,现在微博分享的代码跟微信分享的倒像是一个模子刻出来的了。。。
public class WeiboShareManager { private static WeiboShareManager weiboShareManager; public static WeiboShareManager getInstance(Context context){ if(weiboShareManager == null){ synchronized (WeiboShareManager.class){ weiboShareManager = new WeiboShareManager(context); } } return weiboShareManager; } private Context context; private WbShareHandler shareHandler; private WeiboShareManager(Context context){ this.context = context; WbSdk.install(context, new AuthInfo(context, BuildConfig.WeiboApiKey, "https://api.weibo.com/oauth2/default.html", "all")); shareHandler = new WbShareHandler((Activity)context); shareHandler.registerApp(); } /** * 分享图文消息到微博平台 * @param appName app名称 * @param title 标题 * @param description 描述 * @param imgUrl 图片地址 * @param shareUrl 分享链接URL * @return */ public WeiboShareManager shareTeletextMessageToWeibo(final String appName, final String title, final String description, final String imgUrl, final String shareUrl){ new ImageDownloader(context, imgUrl, new ImageDownloader.OnDownloadListener() { @Override public void onStart() {} @Override public void onDownloading(int total, int progress) {} @Override public void onCompleted(final boolean isSuccessful, final Object result) { ((Activity)context).runOnUiThread(new Runnable() { @Override public void run() { if(isSuccessful){ byte[] picData = (byte[])result; WeiboMultiMessage weiboMultiMessage = new WeiboMultiMessage(); WebpageObject webpageObject = new WebpageObject(); webpageObject.title = title; webpageObject.description = description; webpageObject.setThumbImage(BitmapFactory.decodeByteArray(picData, 0, picData.length)); webpageObject.actionUrl = shareUrl; webpageObject.defaultText = appName; weiboMultiMessage.mediaObject = webpageObject; shareHandler.shareMessage(weiboMultiMessage, true); }else{ Toast.makeText(context.getApplicationContext(), "获取分享资源异常", Toast.LENGTH_SHORT).show(); ((Activity)context).finish(); } } }); } }).start(); return this; } /** * 分享结果回调 * @param intent * @param callback * @return */ public WeiboShareManager doResultIntent(Intent intent, WbShareCallback callback){ if(shareHandler != null) shareHandler.doResultIntent(intent, callback); return this; } }
为了统一便于管理回调结果,所以我们现在把所有回调结果综合起来:
-
分享平台分类: SharePlatform 类
public enum SharePlatform { None, QQ, QZONE, Wechat, WechatZone, Weibo }
-
分享平台参数的并集: ShareContent 类 ,下面我们封装继承于Parcelable(为了传递数据方便)
/**
* Share内容实体类
*/
public class ShareContent implements Parcelable {
public SharePlatform scene = SharePlatform.None;
public String appName;
public String title;
public String description;
public String imgUrl;
public String imgPath;
public String shareUrl;
public ShareContent(){}
public ShareContent(String appName, String title, String description, String imgUrl, String imgPath, String shareUrl) {
this.appName = appName;
this.title = title;
this.description = description;
this.imgUrl = imgUrl;
this.imgPath = imgPath;
this.shareUrl = shareUrl;
}
public ShareContent(SharePlatform scene, String appName, String title, String description, String imgUrl, String imgPath, String shareUrl) {
this.scene = scene;
this.appName = appName;
this.title = title;
this.description = description;
this.imgUrl = imgUrl;
this.imgPath = imgPath;
this.shareUrl = shareUrl;
}
@Override
public String toString() {
return "scene: " + scene + ", appName: " + appName + ", title: " + title + ", description: " + description + ", imgUrl: " + imgUrl +", imgPath: " + imgPath + ", shareUrl: " + shareUrl;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(scene);
dest.writeString(appName);
dest.writeString(title);
dest.writeString(description);
dest.writeString(imgUrl);
dest.writeString(imgPath);
dest.writeString(shareUrl);
}
public static Creator<ShareContent> CREATOR = new Creator<ShareContent>() {
@Override
public ShareContent createFromParcel(Parcel source) {
return new ShareContent(
SharePlatform.valueOf(source.readValue(SharePlatform.class.getClassLoader()).toString()),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString()
);
}
@Override
public ShareContent[] newArray(int size) {
return new ShareContent[size];
}
};
}
-
分享平台分享结果,一般包含3种状态:Failed, Cancel, Success,因此有ShareResult类:
public enum ShareResult { Failed(-1), Cancel(0), Success(1); private int value; ShareResult(int value) { this.value = value; } public static ShareResult valueOf(int value) { switch (value) { case -1: return Failed; case 0: return Cancel; case 1: return Success; } return null; } }
-
回调类,由于涵盖QQ,微信,微博,因此需要实现他们所提供的回调接口,有ShareResultListener 类:
public abstract class ShareResultListener implements IWXAPIEventHandler, IUiListener, WbShareCallback { @Override public void onWbShareSuccess() { onShareResult(SharePlatform.Weibo, ShareResult.Success, "微博分享成功"); } @Override public void onWbShareCancel() { onShareResult(SharePlatform.Weibo, ShareResult.Cancel, "您已取消微博分享"); } @Override public void onWbShareFail() { onShareResult(SharePlatform.Weibo, ShareResult.Failed, "微博分享失败,请稍后重试"); } @Override public void onReq(BaseReq resp) { } @Override public void onResp(BaseResp baseResp) { ShareResult shareResult = ShareResult.Success; String message; switch (baseResp.errCode) { case BaseResp.ErrCode.ERR_OK: message = "微信分享成功"; break; case BaseResp.ErrCode.ERR_USER_CANCEL: message = "微信分享被取消"; shareResult = ShareResult.Cancel; break; case BaseResp.ErrCode.ERR_AUTH_DENIED: message = "微信分享失败"; shareResult = ShareResult.Failed; break; default: message = "微信分享未知"; shareResult = ShareResult.Failed; break; } onShareResult(SharePlatform.Wechat, shareResult, message); } @Override public void onComplete(Object o) { try { JSONObject jsonObject = new JSONObject(o.toString()); boolean isSuccess = jsonObject.optInt("ret") == 0; onShareResult(SharePlatform.QQ, isSuccess ? ShareResult.Success : ShareResult.Failed, isSuccess ? "QQ分享成功": "QQ分享失败,请稍后重试"); } catch (Exception e) { e.printStackTrace(); onShareResult(SharePlatform.QQ, ShareResult.Failed, "QQ分享失败,请稍后重试"); } } @Override public void onError(UiError uiError) { onShareResult(SharePlatform.QQ, ShareResult.Failed, "QQ分享失败,请稍后重试"); } @Override public void onCancel() { onShareResult(SharePlatform.QQ, ShareResult.Cancel, "您取消了QQ分享"); } protected abstract void onShareResult(SharePlatform platform, ShareResult result, String message); }
上面所有架子都已经搭建好了,现在我们该研究如何实现WxEntryActivity.java了。
这里我们打算把WxEntryActivity.java作为一个载体,承载所有结果回调以及界面显示。
-
我们需要先准备一个页面: activity_wx_entry.xml ,大致显示效果如下图:
Screenshot_2017-06-05-15-45-06-627_com.lingkj.and.png<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:fitsSystemWindows="true" android:clipToPadding="false" android:gravity="bottom" tools:background="#333" tools:context=".wxapi.WXEntryActivity" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:background="#fff" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="分享到" android:textSize="17sp" android:padding="15dp" android:textColor="#333" android:layout_width="match_parent" android:layout_height="wrap_content" /> <View android:layout_marginBottom="5dp" android:layout_width="match_parent" android:layout_height="1dp" android:background="#efefef"/> <com.mrper.framework.component.widget.nowrapview.NoWrapGridView android:id="@+id/gvShare" android:numColumns="3" android:verticalSpacing="12dp" android:horizontalSpacing="12dp" android:layout_margin="15dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:padding="20dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/btnCancel" android:background="@drawable/selector_shape_roundrect_orange" android:text="取 消" android:textSize="15sp" android:padding="10dp" android:gravity="center" android:textColor="@color/white" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> </LinearLayout>
-
WxEntryActivity.java的实现,这就需要根据上面的内容进行综合处理了,看客请不要眨眼!
首先我们需要把这个页面做成dialog的形式,因此xml有如下实现:
<style name="ActionSheetDialogActivityTheme" parent="Theme.AppCompat.Dialog"> <item name="android:windowBackground">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowActionBar">false</item> <item name="android:windowFrame">@null</item> <item name="android:windowEnterAnimation">@anim/slide_in_bottom</item> <item name="android:windowExitAnimation">@anim/slide_out_bottom</item> <item name="android:gravity">bottom|center_horizontal</item> <item name="android:layout_gravity">bottom|center_horizontal</item> <item name="android:layout_margin">0dp</item> <item name="android:padding">0dp</item> <item name="android:windowMinWidthMinor">100%</item> <item name="android:windowMinWidthMajor">100%</item> </style>
既然dialog已成,我们就应该根据需求来做分享逻辑啦!
public class WXEntryActivity extends AppCompatActivity {
private Boolean isShowShareUI = false;
private ShareContent shareContent; //要分享的内容
private MaterialProgressDialog loadingDialog; //加载对话框
private SharePlatform sharePlatform = SharePlatform.None;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//以下代码是为了实现沉浸式
ImmersiveStatusBar.setTransparencyBar(this);
ImmersiveStatusBar.setStatusBarColor(this, R.color.colorPrimary);
//获取由前面的页面传递过来的数据,并根据实际情况确定是否绘制UI[setContentView]
IntentBundleDataPicker dataPicker = IntentBundleDataPicker.getInstance(this);
isShowShareUI = dataPicker.getNormalValue("isShowShareUI", false);
if (isShowShareUI != null && isShowShareUI) {
isShowShareUI = true;
kotlin.Pair<Boolean, Object> result = dataPicker.containsKey("shareContent");
if (result.getFirst()) {
if (result.getSecond() instanceof Intent) {
shareContent = ((Intent) result.getSecond()).getParcelableExtra("shareContent");
} else if (result.getSecond() instanceof Bundle) {
shareContent = ((Bundle) result.getSecond()).getParcelable("shareContent");
}
}
//设置窗口属性
setWindowAttribute();
setContentView(R.layout.activity_wx_entry);
//设置控件初始化
initViews();
//初始化加载对话框
initLoadingDialog();
} else {
isShowShareUI = false;
}
}
private void initViews() {
NoWrapGridView gvShare = (NoWrapGridView) findViewById(R.id.gvShare);
TextView btnCancel = (TextView) findViewById(R.id.btnCancel);
gvShare.setAdapter(getShareAdapter());
gvShare.setOnItemClickListener(this::onItemClick);
btnCancel.setOnClickListener(this::onClick);
if (shareContent == null) {
ToastUtil.showShortToast(getApplicationContext(), "分享数据有误,不能完成内容分享!");
this.finish();
}
}
private void setWindowAttribute() {
setTitle("");
Window window = getWindow();
WindowManager.LayoutParams winParams = window.getAttributes();
winParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
winParams.width = WindowManager.LayoutParams.MATCH_PARENT;
winParams.height = WindowManager.LayoutParams.MATCH_PARENT;
winParams.windowAnimations = R.style.ActionSheetDialogAnimationStyle;
winParams.dimAmount = 0.5f;
window.setAttributes(winParams);
setFinishOnTouchOutside(true);
}
private void initLoadingDialog() {
Bundle argument = new Bundle();
argument.putString(MaterialProgressDialog.TIP_TEXT_KEY, "分享中...");
loadingDialog = FragmentDialogUtil.getInstance(MaterialProgressDialog.class, argument);
}
@SuppressWarnings("deprecation")
private void onItemClick(AdapterView<?> adapterView, View view, int position, long itemId) {
if (position == 5) { //复制链接不提供加载对话框
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText("#" + shareContent.title + "#: " + shareContent.shareUrl + " 来自【" + shareContent.appName + "】");
ToastUtil.showShortToast(getApplicationContext(), "复制链接成功!");
this.finish();
} else {
FragmentDialogUtil.show(loadingDialog, this, true);
switch (position) {
case 0://分享到微信朋友圈
shareContent.scene = SharePlatform.WechatZone;
break;
case 1://分享到微信好友
shareContent.scene = SharePlatform.Wechat;
break;
case 2://分享到QQ好友
shareContent.scene = SharePlatform.QQ;
break;
case 3://分享到QQ空间
shareContent.scene = SharePlatform.QZONE;
break;
case 4: //分享到微博
shareContent.scene = SharePlatform.Weibo;
break;
}
sharePlatform = shareContent.scene;
ShareManager.shareTo(this, shareContent, onShareResultListener);
}
}
private void onClick(View vi ```java
```ew) {
switch (view.getId()) {
case R.id.btnCancel: //取消分享
this.finish();
break;
default:
break;
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
switch(sharePlatform){
case QQ:
case QZONE:
WeiboShareManager.getInstance(this).doResultIntent(intent, onShareResultListener);
break;
case Wechat:
case WechatZone:
WechatShareManager.getInstance(this).doResultIntent(intent, onShareResultListener);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TencentShareManager.getInstance(this).onActivityResult(requestCode, resultCode, data, onShareResultListener);
}
/**
* 分享结果回调
*/
private ShareResultListener onShareResultListener = new ShareResultListener() {
@Override
protected void onShareResult(SharePlatform platform, ShareResult result, String message) {
ToastUtil.showShortToast(WXEntryActivity.this.getApplicationContext(), message);
WXEntryActivity.this.finish();
}
};
public ShareAdapter getShareAdapter() {
String[] shareTexts = {"朋友圈", "微信好友", "QQ好友", "QQ空间", "新浪微博", "复制链接"};
int[] icons = {
R.drawable.ic_share_to_wechat_zone,
R.drawable.ic_share_to_wechat,
R.drawable.ic_share_to_qq,
R.drawable.ic_share_to_qzone,
R.drawable.ic_share_to_weibo,
R.drawable.ic_share_to_website_url
};
List<HashMap<String, Object>> items = new ArrayList<>();
for (int i = 0; i < icons.length; i++) {
HashMap<String, Object> item = new HashMap<>();
item.put("icon", icons[i]);
item.put("text", shareTexts[i]);
items.add(item);
}
return new ShareAdapter(this, items);
}
@ItemView(R.layout.griditem_wx_entry_share)
static class ShareAdapter extends BaseListAdapter<HashMap<String, Object>> {
ShareAdapter(@NotNull Context context, @org.jetbrains.annotations.Nullable List<HashMap<String, Object>> dataSource) {
super(context, -1, dataSource);
}
@Override
public void bindValues(@NotNull ViewHolder holder, int position, @NotNull HashMap<String, Object> itemData) {
holder.setImage(R.id.imgLogo, Integer.valueOf(itemData.get("icon").toString()));
holder.setText(R.id.txtName, itemData.get("text").toString());
}
}
}
呼呼,终于大功告成! 今晚加个蛋,哈哈!祝你们码得愉快!