組件暫支持: 微信宜雀,QQ切平,圍脖,復(fù)制粘貼
集成微信相關(guān)的分享
-
按照官方文檔州袒,集成sdk
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
-
按照官方文檔揭绑,集成sdk
-
項(xiàng)目模塊下配置manifest.xml文件
<application> .... <!--這里使用對(duì)話框模式弓候,為了方便把所有的應(yīng)用回調(diào)集中到一起--> <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類
//暫時(shí)補(bǔ)貼出代碼郎哭,請(qǐng)看后面有彩蛋!
?
-
-
如何編寫分享輔助類?使用單例類
下面我們寫一些常用方法
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; /** * 構(gòu)造函數(shù) * @param context 上下文對(duì)象 **/ private WechatShareManager(Context context) { this.context = context; wxapi = WXAPIFactory.createWXAPI(context, BuildConfig.WechatApiKey, true); wxapi.registerApp(BuildConfig.WechatApiKey); } /** * 分享文本到微信 * * @param shareToWhere 分享到哪里 * @param shareText 文本內(nèi)容 */ 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 圖片內(nèi)容 */ 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 標(biāo)題 * @param description 描述 * @param shareUrl 分享的URL鏈接 * @param imgUrl 圖片內(nèi)容 */ 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(); } /** * 結(jié)果數(shù)據(jù)回調(diào) * @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相關(guān)的分享
-
配置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>
-
-
實(shí)現(xiàn)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 上下文對(duì)象 * @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 標(biāo)題名稱 * @param description 內(nèi)容描述 * @param shareUrl 分享的URL * @param imgUrl 圖片地址 * @param callback 結(jié)果回調(diào) */ 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 上下文對(duì)象 * @param appName 應(yīng)用名稱 * @param imgPath 圖片本地路徑 * @param callback 結(jié)果回調(diào) */ 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 上下文對(duì)象 * @param title 標(biāo)題 * @param description 內(nèi)容描述 * @param shareUrl 分享的鏈接 * @param imgUrls 圖片鏈接集合 * @param callback 結(jié)果回調(diào) */ 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); } /** * 應(yīng)用調(diào)用Andriod_SDK接口時(shí),如果要成功接收到回調(diào)依鸥,需要在調(diào)用接口的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: 備注亥至,結(jié)果回調(diào)請(qǐng)一定在Activity中使用onActivityResult,請(qǐng)稍后查看最后的彩蛋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'
-
-
實(shí)現(xiàn)微博分享的代碼贱迟,現(xiàn)在微博分享的代碼跟微信分享的倒像是一個(gè)模子刻出來的了姐扮。。衣吠。
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(); } /** * 分享圖文消息到微博平臺(tái) * @param appName app名稱 * @param title 標(biāo)題 * @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; } /** * 分享結(jié)果回調(diào) * @param intent * @param callback * @return */ public WeiboShareManager doResultIntent(Intent intent, WbShareCallback callback){ if(shareHandler != null) shareHandler.doResultIntent(intent, callback); return this; } }
為了統(tǒng)一便于管理回調(diào)結(jié)果茶敏,所以我們現(xiàn)在把所有回調(diào)結(jié)果綜合起來:
-
分享平臺(tái)分類: SharePlatform 類
public enum SharePlatform { None, QQ, QZONE, Wechat, WechatZone, Weibo }
分享平臺(tái)參數(shù)的并集: ShareContent 類 ,下面我們封裝繼承于Parcelable(為了傳遞數(shù)據(jù)方便)
/**
* Share內(nèi)容實(shí)體類
*/
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];
}
};
}
-
分享平臺(tái)分享結(jié)果缚俏,一般包含3種狀態(tài):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; } }
-
回調(diào)類,由于涵蓋QQ忧换,微信恬惯,微博,因此需要實(shí)現(xiàn)他們所提供的回調(diào)接口亚茬,有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, "微博分享失敗酪耳,請(qǐng)稍后重試"); } @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分享失敗,請(qǐng)稍后重試"); } catch (Exception e) { e.printStackTrace(); onShareResult(SharePlatform.QQ, ShareResult.Failed, "QQ分享失敗刹缝,請(qǐng)稍后重試"); } } @Override public void onError(UiError uiError) { onShareResult(SharePlatform.QQ, ShareResult.Failed, "QQ分享失敗碗暗,請(qǐng)稍后重試"); } @Override public void onCancel() { onShareResult(SharePlatform.QQ, ShareResult.Cancel, "您取消了QQ分享"); } protected abstract void onShareResult(SharePlatform platform, ShareResult result, String message); }
上面所有架子都已經(jīng)搭建好了,現(xiàn)在我們該研究如何實(shí)現(xiàn)WxEntryActivity.java了赞草。
? 這里我們打算把WxEntryActivity.java作為一個(gè)載體讹堤,承載所有結(jié)果回調(diào)以及界面顯示。
-
我們需要先準(zhǔn)備一個(gè)頁面: activity_wx_entry.xml 厨疙,大致顯示效果如下圖:
?
<?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的實(shí)現(xiàn)洲守,這就需要根據(jù)上面的內(nèi)容進(jìn)行綜合處理了疑务,看客請(qǐng)不要眨眼!
首先我們需要把這個(gè)頁面做成dialog的形式梗醇,因此xml有如下實(shí)現(xiàn):
<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已成知允,我們就應(yīng)該根據(jù)需求來做分享邏輯啦!
public class WXEntryActivity extends AppCompatActivity {
private Boolean isShowShareUI = false;
private ShareContent shareContent; //要分享的內(nèi)容
private MaterialProgressDialog loadingDialog; //加載對(duì)話框
private SharePlatform sharePlatform = SharePlatform.None;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//以下代碼是為了實(shí)現(xiàn)沉浸式
ImmersiveStatusBar.setTransparencyBar(this);
ImmersiveStatusBar.setStatusBarColor(this, R.color.colorPrimary);
//獲取由前面的頁面?zhèn)鬟f過來的數(shù)據(jù)叙谨,并根據(jù)實(shí)際情況確定是否繪制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");
}
}
//設(shè)置窗口屬性
setWindowAttribute();
setContentView(R.layout.activity_wx_entry);
//設(shè)置控件初始化
initViews();
//初始化加載對(duì)話框
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(), "分享數(shù)據(jù)有誤温鸽,不能完成內(nèi)容分享!");
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) { //復(fù)制鏈接不提供加載對(duì)話框
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText("#" + shareContent.title + "#: " + shareContent.shareUrl + " 來自【" + shareContent.appName + "】");
ToastUtil.showShortToast(getApplicationContext(), "復(fù)制鏈接成功!");
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);
}
/**
* 分享結(jié)果回調(diào)
*/
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空間", "新浪微博", "復(fù)制鏈接"};
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());
}
}
}
呼呼,終于大功告成! 今晚加個(gè)蛋手负,哈哈涤垫!祝你們碼得愉快!