安卓三方集成Android开发Android开发

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

2017-06-05  本文已影响344人  Cosecant

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

集成微信相关的分享

集成QQ相关的分享

集成新浪微博的分享

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

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

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

上一篇下一篇

猜你喜欢

热点阅读