Android平台分享之微博
2016-06-23 本文已影响0人
Blue_Kid
- 初始化
//1. 将应用注册到微博客户端
private IWeiboShareAPI mWeiboShareAPI; //weibo
mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, BaseConstants.SINA_WEIBO_API_KEY);
mWeiboShareAPI.registerApp();
- 封装分享类
public class WBShareUtil {
private static final String TAG = WBShareUtil.class.getSimpleName();
private Activity mActivity;
public WBShareUtil(Activity activity) {
this.mActivity = activity;
}
public void shareToWB(IWeiboShareAPI mShareAPI, Bitmap bitmap, String text) {
Log.i(TAG, "shareToWeibo");
//2.准备分享的文本和图片
final TextObject mTO = new TextObject();
mTO.text = text;
ImageObject mIO = new ImageObject();
//Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_calendar_left_arrow_56);
mIO.setImageObject(bitmap); //图片 参数问题 导致无法调用客户端
//3.初始化微博的分享信息
WeiboMultiMessage mWeiboMultiMsg = new WeiboMultiMessage();
mWeiboMultiMsg.textObject = mTO;
mWeiboMultiMsg.imageObject = mIO;
//3.建立分享请求
SendMultiMessageToWeiboRequest mRequest = new SendMultiMessageToWeiboRequest();
mRequest.transaction = String.valueOf(System.currentTimeMillis());
mRequest.multiMessage = mWeiboMultiMsg;
//4.分享
AuthInfo mAuthInfo = new AuthInfo(mActivity, BaseConstants.SINA_WEIBO_API_KEY,
BaseConstants.SINA_WEIBO_REDIRECT_URL, BaseConstants.SINA_WEIBO_SCOPE);
final String tokenValue = PreferenceUtil.getString(PreferenceUtil.WEIBO_TOKEN,
PreferenceUtil.WEIBO_TOKEN_VALUE);
mShareAPI.sendRequest(mActivity, mRequest, mAuthInfo, tokenValue, new WeiboAuthListener() {
@Override
public void onComplete(Bundle bundle) {
Oauth2AccessToken mToken = Oauth2AccessToken.parseAccessToken(bundle);
if ( mToken.isSessionValid() ) {
Log.i(TAG, "onCompleted ----> mToken.getToken() = " + mToken.getToken());
PreferenceUtil.commitString(PreferenceUtil.WEIBO_TOKEN, mToken.getToken()); //存储token
} else {
// 以下几种情况,您会收到 Code:
// 1. 当您未在平台上注册的应用程序的包名与签名时;
// 2. 当您注册的应用程序包名与签名不正确时;
// 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
String code = bundle.getString("code");
String message = mActivity.getString(R.string.WEIBO_AUTH_FAILED);
if (!TextUtils.isEmpty(code)) {
Log.i(TAG, "msg = " + message + code);
}
Toast.makeText(mActivity, message, Toast.LENGTH_LONG).show();
}
}
@Override
public void onWeiboException(WeiboException e) {
e.printStackTrace();
}
@Override
public void onCancel() {
Toast.makeText(mActivity, mActivity.getString(R.string.WEIBO_SHARE_CANCELED),
Toast.LENGTH_SHORT).show();
}
});
}
}