Java - Android集成社会化分享组件

组件暂支持: 微信,QQ,围脖,复制粘贴

集成微信相关的分享

  • 按照官方文档,集成sdk

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

    1. 项目模块下配置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>
      
    2. 添加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

    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>
    
  • 实现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

    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'
      
  • 实现微博分享的代码,现在微博分享的代码跟微信分享的倒像是一个模子刻出来的了。。。

    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;
        }
    
    }
    

为了统一便于管理回调结果,所以我们现在把所有回调结果综合起来:

  1. 分享平台分类: SharePlatform

    public enum SharePlatform {
        None,
        QQ,
        QZONE,
        Wechat,
        WechatZone,
        Weibo
    }
    
  2. 分享平台参数的并集: 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];
        }
    };

}
  1. 分享平台分享结果,一般包含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;
        }
    
    }
    
  2. 回调类,由于涵盖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作为一个载体,承载所有结果回调以及界面显示。

  1. 我们需要先准备一个页面: 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的实现,这就需要根据上面的内容进行综合处理了,看客请不要眨眼!

    首先我们需要把这个页面做成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());
         }
     }
 }

呼呼,终于大功告成! 今晚加个蛋,哈哈!祝你们码得愉快!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,580评论 18 139
  • 最近由于公司想弄一个新手推荐活动,因为是推荐活动,必须借用现在流行的社交软件进行各种分享,只要形式有微信分享到好友...
    toskyline阅读 2,134评论 0 2
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,560评论 18 399
  • 9af0e05c6c75阅读 355评论 0 0
  • 前言 最近项目中需要分享功能,就集成官方的分享,特此记录下,便于自己后续回顾。注意:我都是分享的网址即URL,其他...
    Jsonzhang阅读 6,107评论 2 11