Android implementation of micro-letter, micro-bo, micro-trust friends circle, QQ sharing functions _android

Source: Internet
Author: User
Tags auth

Android implementation of micro-letter, micro-bo, micro-trust friends circle, QQ sharing function

First, to the respective developer platform to register the corresponding key value, the introduction of the relevant jar package, permissions, etc.

Second, Shareutil tool class

Import android.app.Activity;
Import Android.content.Context;
Import Android.content.pm.PackageInfo;
Import Android.content.pm.PackageManager;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;

Import Android.os.Bundle;
Import Com.sina.weibo.sdk.api.ImageObject;
Import Com.sina.weibo.sdk.api.TextObject;
Import Com.sina.weibo.sdk.api.WeiboMultiMessage;
Import Com.sina.weibo.sdk.api.share.IWeiboShareAPI;
Import Com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
Import Com.sina.weibo.sdk.api.share.WeiboShareSDK;
Import Com.sina.weibo.sdk.auth.AuthInfo;
Import Com.sina.weibo.sdk.auth.Oauth2AccessToken;
Import Com.sina.weibo.sdk.auth.WeiboAuthListener;
Import com.sina.weibo.sdk.exception.WeiboException;
Import Com.tencent.connect.share.QQShare;
Import Com.tencent.mm.sdk.modelmsg.SendMessageToWX;
Import Com.tencent.mm.sdk.modelmsg.WXMediaMessage;
Import Com.tencent.mm.sdk.modelmsg.WXWebpageObject;
Import Com.tencent.mm.sdk.openapi.IWXAPI; Import com.tencent.mm.Sdk.openapi.WXAPIFactory;
Import Com.tencent.tauth.IUiListener;

Import com.tencent.tauth.Tencent;

Import java.util.List;
Import CN.HNSHANGYU.MAKER.R;
Import Cn.hnshangyu.maker.weibo.AccessTokenKeeper;

Import cn.hnshangyu.maker.weibo.Constants; 
 /** * ============================================ * FileName: Shareutil.java * Date: 2016-08-17 14:58 * Description: Share Help class * Version: 1.0 * * ============================================/public class Shareutil {/** * microblogging micro Bo Share Interface instance * * public static
  Iweiboshareapi Mweiboshareapi;
  Micro-letter sharing public static final String weixin_share_app_id = "wx0c********88488d";

  public static Iwxapi Weixin_api;
  public static final String qq_app_id = "11****5659";

  public static Tencent mtencent; public static void shareqq (activity activity, String Sharepath, Iuilistener listener) {//qq share mtencent = Tencent.
    CreateInstance (qq_app_id, activity); if (isqqclientavailable (activity)) {//String content = Activity.getresources (). getString (r.string. ivqrcode_content);
      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, "######");
      Params.putstring (qqshare.share_to_qq_summary, "############# ...");
Params.putstring (Qqshare.share_to_qq_target_url, Sharepath);

      Params.putstring (Qqshare.share_to_qq_image_url, "https://www.baidu.com/img/bd_logo1.png");
    MTENCENT.SHARETOQQ (activity, params, listener); else {uiutils.showtoast (activity, "Check to see if the latest version of qq! is installed
    "); }/** * To determine whether QQ is available * * @param context * @return/private static Boolean isqqclientavailable (Contex
    T context) {final Packagemanager Packagemanager = Context.getpackagemanager ();
    List<packageinfo> pinfo = packagemanager.getinstalledpackages (0);
        if (pinfo!= null) {for (int i = 0; i < pinfo.size (); i++) {String pn = pinfo.get (i). PackageName; if (Pn.equals ("CoM.tencent.mobileqq ")) {return true;
  //** If you return false QQ's light chat version will also show the installation of a new version, true he will automatically download the new version return true; public static void Shareweibo (final activity activity, String Sharepath) {//Weibo MWEIBOSHAREAPI = weibosharesd

    K.createweiboapi (activity, Constants.app_key); 1.
    Initialize the microblogging sharing message weibomultimessage Weibomessage = new Weibomultimessage ();
    Weibomessage.mediaobject = getimageobj (activity);

    Weibomessage.textobject = gettextobj (activity, sharepath);
    Sendmultimessagetoweiborequest request = new Sendmultimessagetoweiborequest ();
    Uniquely identifies a request with transaction = Request.transaction = String.valueof (System.currenttimemillis ());

    Request.multimessage = Weibomessage; if (mweiboshareapi.isweiboappinstalled () && Mweiboshareapi.isweiboappsupportapi ()) {Mweiboshareapi.registe  RAPP (); Register the application to the microblogging client//3.
    Send request message to Weibo, arouse microblogging sharing interface Mweiboshareapi.sendrequest (activity, request); else {AuthInfo MauthiNFO = new AuthInfo (activity, Constants.app_key, Constants.redirect_url, Constants.scope);
      Oauth2accesstoken Accesstoken = Accesstokenkeeper.readaccesstoken (activity);
      String token = "";
      if (Accesstoken!= null) {token = Accesstoken.gettoken ();
        Mweiboshareapi.sendrequest (activity, request, Mauthinfo, token, new Weiboauthlistener () {@Override public void OnComplete (Bundle Bundle) {Oauth2accesstoken Newtoken = Oauth2accesstoken.parseaccesstoken (Bundle
          );

          Accesstokenkeeper.writeaccesstoken (activity, Newtoken);
        Uiutils.showtoast (activity, "onauthorizecomplete token =" + Newtoken.gettoken ()); @Override public void Onweiboexception (Weiboexception e) {uiutils.showtoast (activity, "sharing error"
        );
        @Override public void OnCancel () {Uiutils.showtoast (activity, "share cancellation");
    }
      }); }} private static Textobject Gettextobj (ActIvity activity, String sharepath) {textobject textobject = new Textobject ();
    Textobject.text = "##################...@" + sharepath;
    Bitmap Bitmap = Bitmapfactory.decoderesource (Activity.getresources (), r.mipmap.ic_launcher);
    Textobject.setthumbimage (bitmap);
  return textobject;
   /** * Creates a picture message object.
   * * @return Picture Message object. * * private static Imageobject getimageobj (activity activity) {Imageobject imageobject = new Imageobject ();//Bi
    Tmapdrawable bitmapdrawable = (bitmapdrawable) mimageview.getdrawable (); Set thumbnails.
    Note: The final compressed thumbnail size must not exceed 32kb.
    Bitmap Bitmap = Bitmapfactory.decoderesource (Activity.getresources (), r.mipmap.ic_launcher);
    Imageobject.setimageobject (bitmap);
  return imageobject;
  Static Sendmessagetowx.req Req;

  private static final int thumb_size = 150;
      public static void sharewechatcircle (activity activity, String Sharepath) {if (Linkweixin (activity, Sharepath)) { Req.scene = SendMessageToWX.Req.WXSceneTimeline;
    Weixin_api.sendreq (req);
      } public static void Sharewechat (activity activity, String Sharepath) {if (Linkweixin (activity, Sharepath)) {
      Req.scene = SendMessageToWX.Req.WXSceneSession;
    Weixin_api.sendreq (req); }//micro-letter Sharing private static Boolean linkweixin (activity activity, String Sharepath) {//through Wxapifactory factory, get iwxap
    Example of I weixin_api = Wxapifactory.createwxapi (activity, weixin_share_app_id, true); if (weixin_api.iswxappinstalled () && Weixin_api.iswxappsupportapi ()) {Weixin_api.registerapp (WEIXIN_SHARE_

      APP_ID);
      Wxwebpageobject webpageobject = new Wxwebpageobject ();

      Webpageobject.webpageurl = Sharepath;
      Wxmediamessage msg = new Wxmediamessage ();
      Msg.mediaobject = Webpageobject;
      Bitmap Bitmap = Bitmapfactory.decoderesource (Activity.getresources (), r.mipmap.ic_launcher);
      Msg.setthumbimage (bitmap);
      Msg.title = "######"; Msg.description = "################### ...";
      req = new Sendmessagetowx.req ();
      Req.transaction = buildtransaction ("webpage");

      Req.message = msg;
    return true; else {uiutils.showtoast (activity, "Check to see if the latest version of the micro-letter is installed!")
      ");
    return false; }} private static string Buildtransaction (final String type) {return (type = null)?
  String.valueof (System.currenttimemillis ()): Type + system.currenttimemillis ();

 }
}

third, sharing interface

Import android.content.Intent;
Import Android.graphics.Bitmap;
Import Android.os.Bundle;
Import android.support.annotation.Nullable;
Import Android.view.View;

Import Android.widget.ImageView;
Import com.google.zxing.WriterException;
Import Com.sina.weibo.sdk.api.share.BaseResponse;
Import Com.sina.weibo.sdk.api.share.IWeiboHandler;
Import Com.sina.weibo.sdk.api.share.IWeiboShareAPI;
Import Com.sina.weibo.sdk.api.share.WeiboShareSDK;
Import com.sina.weibo.sdk.constant.WBConstants;
Import Com.tencent.tauth.IUiListener;
Import com.tencent.tauth.Tencent;

Import Com.tencent.tauth.UiError; Import Butterknife.
BindView;
Import CN.HNSHANGYU.MAKER.R;
Import cn.hnshangyu.maker.base.BaseActivity;
Import Cn.hnshangyu.maker.ui.personal.zxing.EncodingHandler;
Import Cn.hnshangyu.maker.util.ShareUtil;
Import Cn.hnshangyu.maker.util.UIUtils;

Import cn.hnshangyu.maker.weibo.Constants; public class Invitefriendsactivity extends Baseactivity implements Iweibohandler.response {@BindView (R.ID.IV_QRCODE) ImageView Ivqrcode;
  @BindView (R.ID.IV_SHARE_QQ) ImageView ivshareqq;
  @BindView (R.id.iv_share_weibo) ImageView Ivshareweibo;
  @BindView (r.id.iv_share_weixin) ImageView ivshareweixin;

  @BindView (r.id.iv_share_circle_friends) ImageView ivsharecirclefriends;

  Private Bitmap Qrcodebitmap;

  /** * Micro Bo Share Interface instance * * Private IWEIBOSHAREAPI MWEIBOSHAREAPI = null;

  Share link private String sharepath;
  @Override protected int Getlayoutid () {return r.layout.activity_invite_friends;

    } @Override protected void Onnewintent (Intent Intent) {super.onnewintent (Intent); After the current application is invoked and shared, and returned to the current application, the function needs to be called here//to receive the data returned by the microblogging client; execution succeeds, returns True, and calls//{@link Iweibohandler.response#onrespon
  SE}; failure returns false and does not invoke the callback Mweiboshareapi.handleweiboresponse (intent, this); /** * Initializes the control (this method must be implemented)/@Override protected void Initview () {sharepath = Getresources (). getString (R.st
    Ring.ivqrcode_content);
    Onshowtopback (FALSE); OnshowtitleBack (true);
    Settitletext (R.string.invite_friends);

    Showqrcode ();

    Create a microblogging sharing interface instance Mweiboshareapi = Weibosharesdk.createweiboapi (this, constants.app_key);
    Registered third party applications to the microblogging client, the application will be displayed in the microblogging application list after successful registration.

    However, the Attachment column integration sharing permissions need to cooperate with the application, please see Demo tips//Note: Be sure to register in advance, that is, when the interface initialization or application initialization, register Mweiboshareapi.registerapp ();
  Initlistener ();

    @Override protected void OnCreate (@Nullable Bundle savedinstancestate) {super.oncreate (savedinstancestate); When an activity is reinitialized (the activity is in the background, it may be killed due to insufficient memory),//need to call {@link Iweiboshareapi#handleweiboresponse} to receive the microblogging client
    The returned data. Execution succeeds, returns True, and calls {@link iweibohandler.response#onresponse};//Failure returns false and does not invoke the above callback if (Savedinstancestate!= nul
    L) {mweiboshareapi.handleweiboresponse (Getintent (), this); } private void Showqrcode () {//Generate two-dimensional code picture, the first parameter is the contents of the two-dimensional code, the second parameter is the side length of the square picture, in pixels//String content = "http://m.360b Uyimg.com/mobilecms/s300x98_jfs/t1363/77/1381395719/60705/ce91ad5c/55dd271an49Efd216.jpg ";
    Content = Getresources (). getString (r.string.ivqrcode_content);

      try {qrcodebitmap = Encodinghandler.createqrcode (Sharepath, 400);
    Ivqrcode.setimagebitmap (QRCODEBITMAP);
    catch (Writerexception e) {e.printstacktrace ();
    }} private void Initlistener () {Ivshareqq.setonclicklistener (this);
    Ivshareweibo.setonclicklistener (this);
    Ivshareweixin.setonclicklistener (this);
  Ivsharecirclefriends.setonclicklistener (this);
    } @Override protected void Oninitclick (View v) {Super.oninitclick (v);
        Switch (V.getid ()) {case r.id.iv_share_qq:shareutil.shareqq (mactivity, Sharepath, Sharelistener);
      Break
        Case R.id.iv_share_weibo:shareutil.shareweibo (mactivity, Sharepath);
      Break
        Case R.id.iv_share_weixin:shareutil.sharewechat (mactivity, Sharepath);
      Break Case R.id.iv_share_circle_friends:shareutil.sharewechatcircle (mactivity, Sharepath);
    Break @Override public void Onresponse (Baseresponse baseresponse) {if (baseresponse!= null) {switch (bas
          Eresponse.errcode) {case WBConstants.ErrorCode.ERR_OK:UIUtils.showToast (Mcontext, "sharing success");
        Break
          Case WBConstants.ErrorCode.ERR_CANCEL:UIUtils.showToast (Mcontext, "share cancellation");
        Break
          Case WBConstants.ErrorCode.ERR_FAIL:UIUtils.showToast (Mcontext, "sharing failure");
      Break }} private Iuilistener Sharelistener = new Iuilistener () {@Override public void OnComplete (Object o)
    {Uiutils.showtoast (Mcontext, "sharing success");
    @Override public void OnError (Uierror uierror) {uiutils.showtoast (Mcontext, "Share Error");

  @Override public void OnCancel () {}}; protected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (Requestcode = = Com.tencent.connect . Common.
    Constants.request_qq_share) {  Tencent.onactivityresultdata (Requestcode, ResultCode, data, Sharelistener);

 }
  }
}

four, constants class

/** * This class defines the parameters required for microblogging authorization. * * Public interface Constants {/** * currently applied App_key, third party applications should use their own app_key replace the App_key/public static final St

  Ring App_key = "16#### #007";
   /** * Currently applied callback page, Third-party applications can use their own callback page.
   * <p/> * <p> * NOTE: The authorization callback page is not visible to the user for mobile client applications, so the definition of what form will not affect, * but no definition will not be able to use the SDK authentication login. * Recommend using default callback page: https://api.weibo.com/oauth2/default.html * </p>//public static final String Redirect_url =
  "Http://www.sina.com";
  public static final String Redirect_url = "https://api.weibo.com/oauth2/default.html"; /** * Scope is a parameter of the authorize interface in the OAuth2.0 authorization mechanism.
   Through Scope, the platform will open more micro-blog * Core features to developers, but also enhance user privacy protection, enhance the user experience, the user in the new OAuth2.0 Licensing page has the right to select the application-given function.
   * <p/> * We use the Sina Weibo open platform--> Management Center--> My Application--> interface management, can see what we have currently have the interface of the * usage rights, advanced permissions need to apply.
   * <p/> * Current scope supports passing in multiple scope permissions, separated by commas. * <p/> * about which OPENAPI need permission request, please check: Http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI * about Scope concept and considerations, please check: http: Open.weibo.coM/wiki/scope * * public static final String Scope = "Email,direct_messages_read,direct_messages_write,"  + "Friendships_groups_read,friendships_groups_write,statuses_to_me_read," + "follow_app_official_microblog," +
"Invitation_write";

 }

  Thank you for reading, I hope to help you, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.