Java - Android集成社會(huì)化分享組件

組件暫支持: 微信宜雀,QQ切平,圍脖,復(fù)制粘貼

集成微信相關(guān)的分享

  • 按照官方文檔州袒,集成sdk

    compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
    
  • 按照官方文檔揭绑,集成sdk

    1. 項(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>
      
    2. 添加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

    1. 添加依賴

        //騰訊QQSDK
          compile files('libs/mta-sdk-1.6.2.jar')
          compile files('libs/open_sdk_r5788.jar')
      
    2. 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

    1. 配置根目錄的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/" }
          }
      }
      
    2. 配置所在模塊的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é)果綜合起來:

  1. 分享平臺(tái)分類: SharePlatform

    public enum SharePlatform {
        None,
        QQ,
        QZONE,
        Wechat,
        WechatZone,
        Weibo
    }
    
  2. 分享平臺(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];
        }
    };

}
  1. 分享平臺(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;
        }
    
    }
    
  2. 回調(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)以及界面顯示。

  1. 我們需要先準(zhǔn)備一個(gè)頁面: 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>
    
  1. 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è)蛋手负,哈哈涤垫!祝你們碼得愉快!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末竟终,一起剝皮案震驚了整個(gè)濱河市蝠猬,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌统捶,老刑警劉巖榆芦,帶你破解...
    沈念sama閱讀 206,214評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異喘鸟,居然都是意外死亡匆绣,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門什黑,熙熙樓的掌柜王于貴愁眉苦臉地迎上來崎淳,“玉大人,你說我怎么就攤上這事兑凿】Γ” “怎么了?”我有些...
    開封第一講書人閱讀 152,543評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵礼华,是天一觀的道長咐鹤。 經(jīng)常有香客問我,道長圣絮,這世上最難降的妖魔是什么祈惶? 我笑而不...
    開封第一講書人閱讀 55,221評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮扮匠,結(jié)果婚禮上捧请,老公的妹妹穿的比我還像新娘。我一直安慰自己棒搜,他們只是感情好疹蛉,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評(píng)論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著力麸,像睡著了一般可款。 火紅的嫁衣襯著肌膚如雪育韩。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,007評(píng)論 1 284
  • 那天闺鲸,我揣著相機(jī)與錄音筋讨,去河邊找鬼。 笑死摸恍,一個(gè)胖子當(dāng)著我的面吹牛悉罕,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播立镶,決...
    沈念sama閱讀 38,313評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼壁袄,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了谜慌?” 一聲冷哼從身側(cè)響起然想,我...
    開封第一講書人閱讀 36,956評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎欣范,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體令哟,經(jīng)...
    沈念sama閱讀 43,441評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡恼琼,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了屏富。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片晴竞。...
    茶點(diǎn)故事閱讀 38,018評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖狠半,靈堂內(nèi)的尸體忽然破棺而出噩死,到底是詐尸還是另有隱情,我是刑警寧澤神年,帶...
    沈念sama閱讀 33,685評(píng)論 4 322
  • 正文 年R本政府宣布已维,位于F島的核電站,受9級(jí)特大地震影響已日,放射性物質(zhì)發(fā)生泄漏垛耳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評(píng)論 3 307
  • 文/蒙蒙 一飘千、第九天 我趴在偏房一處隱蔽的房頂上張望堂鲜。 院中可真熱鬧,春花似錦护奈、人聲如沸缔莲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽痴奏。三九已至磺箕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間抛虫,已是汗流浹背松靡。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評(píng)論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留建椰,地道東北人雕欺。 一個(gè)月前我還...
    沈念sama閱讀 45,467評(píng)論 2 352
  • 正文 我出身青樓,卻偏偏與公主長得像棉姐,于是被迫代替她去往敵國和親屠列。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理伞矩,服務(wù)發(fā)現(xiàn)笛洛,斷路器,智...
    卡卡羅2017閱讀 134,599評(píng)論 18 139
  • 最近由于公司想弄一個(gè)新手推薦活動(dòng)乃坤,因?yàn)槭峭扑]活動(dòng)苛让,必須借用現(xiàn)在流行的社交軟件進(jìn)行各種分享,只要形式有微信分享到好友...
    toskyline閱讀 2,134評(píng)論 0 2
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法湿诊,類相關(guān)的語法狱杰,內(nèi)部類的語法,繼承相關(guān)的語法厅须,異常的語法仿畸,線程的語...
    子非魚_t_閱讀 31,581評(píng)論 18 399
  • 9af0e05c6c75閱讀 355評(píng)論 0 0
  • 前言 最近項(xiàng)目中需要分享功能,就集成官方的分享镀层,特此記錄下镰禾,便于自己后續(xù)回顧。注意:我都是分享的網(wǎng)址即URL唱逢,其他...
    Jsonzhang閱讀 6,111評(píng)論 2 11