編輯:關於Android編程
Android 實現微信,微博,微信朋友圈,QQ分享的功能
一、去各自所在的開發者平台注冊相應的Key值;引入相關jar包、權限等
二、ShareUtil工具類
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; /** * ============================================ * 文件名:ShareUtil.java * 日期:2016-08-17 14:58 * 描述:分享幫助類 * 版本:1.0 * * ============================================ */ public class ShareUtil { /** * 微博微博分享接口實例 */ public static IWeiboShareAPI mWeiboShareAPI; //微信分享 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分享 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, "請檢查是否安裝最新版QQ!"); } } /** * 判斷qq是否可用 * * @param context * @return */ private static boolean isQQClientAvailable(Context 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; } } } //**如果返回false qq的輕聊版也會顯示安裝新版本,true他會自動下載新版本 return true; } public static void shareWeiBo(final Activity activity, String sharePath) { //微博 mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(activity, Constants.APP_KEY); // 1. 初始化微博的分享消息 WeiboMultiMessage weiboMessage = new WeiboMultiMessage(); weiboMessage.mediaObject = getImageObj(activity); weiboMessage.textObject = getTextObj(activity, sharePath); SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest(); // 用transaction唯一標識一個請求 request.transaction = String.valueOf(System.currentTimeMillis()); request.multiMessage = weiboMessage; if (mWeiboShareAPI.isWeiboAppInstalled() && mWeiboShareAPI.isWeiboAppSupportAPI()) { mWeiboShareAPI.registerApp(); // 將應用注冊到微博客戶端 // 3. 發送請求消息到微博,喚起微博分享界面 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, "分享出錯"); } @Override public void onCancel() { UIUtils.showToast(activity, "分享取消"); } }); } } 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; } /** * 創建圖片消息對象。 * * @return 圖片消息對象。 */ private static ImageObject getImageObj(Activity activity) { ImageObject imageObject = new ImageObject(); // BitmapDrawable bitmapDrawable = (BitmapDrawable) mImageView.getDrawable(); //設置縮略圖。 注意:最終壓縮過的縮略圖大小不得超過 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); } } //微信分享 private static boolean linkWeiXin(Activity activity, String sharePath) { // 通過WXAPIFactory工廠,獲取IWXAPI的實例 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, "請檢查是否安裝最新版微信!"); return false; } } private static String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); } }
三、分享界面
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; /** * 微博微博分享接口實例 */ private IWeiboShareAPI mWeiboShareAPI = null; //分享鏈接 private String sharePath; @Override protected int getLayoutId() { return R.layout.activity_invite_friends; } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 從當前應用喚起微博並進行分享後,返回到當前應用時,需要在此處調用該函數 // 來接收微博客戶端返回的數據;執行成功,返回 true,並調用 // {@link IWeiboHandler.Response#onResponse};失敗返回 false,不調用上述回調 mWeiboShareAPI.handleWeiboResponse(intent, this); } /** * 初始化控件(必須實現此方法) */ @Override protected void initView() { sharePath = getResources().getString(R.string.ivQrcode_content); onShowTopBack(false); onShowTitleBack(true); setTitleText(R.string.invite_friends); showQRCode(); // 創建微博分享接口實例 mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constants.APP_KEY); // 注冊第三方應用到微博客戶端中,注冊成功後該應用將顯示在微博的應用列表中。 // 但該附件欄集成分享權限需要合作申請,詳情請查看 Demo 提示 // NOTE:請務必提前注冊,即界面初始化的時候或是應用程序初始化時,進行注冊 mWeiboShareAPI.registerApp(); initListener(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 當 Activity 被重新初始化時(該 Activity 處於後台時,可能會由於內存不足被殺掉了), // 需要調用 {@link IWeiboShareAPI#handleWeiboResponse} 來接收微博客戶端返回的數據。 // 執行成功,返回 true,並調用 {@link IWeiboHandler.Response#onResponse}; // 失敗返回 false,不調用上述回調 if (savedInstanceState != null) { mWeiboShareAPI.handleWeiboResponse(getIntent(), this); } } private void showQRCode() { //生成二維碼圖片,第一個參數是二維碼的內容,第二個參數是正方形圖片的邊長,單位是像素 // String content = "http://m.360buyimg.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 (baseResponse.errCode) { case WBConstants.ErrorCode.ERR_OK: UIUtils.showToast(mContext, "分享成功"); break; case WBConstants.ErrorCode.ERR_CANCEL: UIUtils.showToast(mContext, "分享取消"); break; case WBConstants.ErrorCode.ERR_FAIL: UIUtils.showToast(mContext, "分享失敗"); break; } } } private IUiListener shareListener = new IUiListener() { @Override public void onComplete(Object o) { UIUtils.showToast(mContext, "分享成功"); } @Override public void onError(UiError uiError) { UIUtils.showToast(mContext, "分享出錯"); } @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); } } }
四、Constants類
/** * 該類定義了微博授權時所需要的參數。 */ public interface Constants { /** * 當前 應用的 APP_KEY,第三方應用應該使用自己的 APP_KEY 替換該 APP_KEY */ public static final String APP_KEY = "16#####007"; /** * 當前 應用的回調頁,第三方應用可以使用自己的回調頁。 * <p/> * <p> * 注:關於授權回調頁對移動客戶端應用來說對用戶是不可見的,所以定義為何種形式都將不影響, * 但是沒有定義將無法使用 SDK 認證登錄。 * 建議使用默認回調頁: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 是 OAuth2.0 授權機制中 authorize 接口的一個參數。通過 Scope,平台將開放更多的微博 * 核心功能給開發者,同時也加強用戶隱私保護,提升了用戶體驗,用戶在新 OAuth2.0 授權頁中有權利 * 選擇賦予應用的功能。 * <p/> * 我們通過新浪微博開放平台-->管理中心-->我的應用-->接口管理處,能看到我們目前已有哪些接口的 * 使用權限,高級權限需要進行申請。 * <p/> * 目前 Scope 支持傳入多個 Scope 權限,用逗號分隔。 * <p/> * 有關哪些 OpenAPI 需要權限申請,請查看:http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI * 關於 Scope 概念及注意事項,請查看: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"; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
ES文件浏覽器連接電腦顯示登錄失敗。之前在連著電腦看著電視,不知道手機怎麼了,現在連接不上,還顯示登錄失敗。現在不知道怎麼辦。小編來給大家演示一下,當ES浏
這裡用的mac版本的AndroidStudio1. 執行組合快捷鍵command+”,”,打開AS偏好設置頁面,找到plugin選項,輸入Parc
ActiveAndroid和OrmLite都是ORM架構的數據庫,之前使用的是OrmLite,今天研究了一番ActiveAndroid,發現兩者各有千秋,在代碼上,Act
一、配置NDK環境第一步:在AndroidStudio中配置ndk環境需要下載ndk包,在AndroidStudio中File-->ProjectStructure