Java implementation of sina weibo Shared code instances
- 2020-04-01 03:44:12
- OfStack
Weibo. Java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_center);
//Create a microblog instance
mWeiboAuth = new WeiboAuth(this, Constants.APP_KEY,
Constants.REDIRECT_URL, Constants.SCOPE);
//
mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constants.APP_KEY);
//
when the Activity is reinitialized (it may be killed due to a lack of memory when the Activity is in the background)
//You need to call {@link IWeiboShareAPI#handleWeiboResponse} to receive the data returned by the microblogging client. < br / >
//Execute successfully, return true, and call {@link iweibohandler. Response#onResponse}; < br / >
//Failure returns false without calling the above callback
if (savedInstanceState != null) {
mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
}
}
/**
* Verify that the user has sina weibo installed
*/
public void isNotInstall() {
try {
//Check whether the micro-blog client environment is normal. If the micro-blog is not installed, a dialog box will pop up asking the user to download the micro-blog client
if (mWeiboShareAPI.checkEnvironment(true)) {
//Register a third-party application to the weibo client. After successful registration, the application will be displayed in the list of weibo applications. < br / >
//However, the attachment bar requires cooperation application for integration and sharing rights. For details, please see the Demo prompt
mWeiboShareAPI.registerApp();
startSinaShare();
}
} catch (WeiboShareException e) {
e.printStackTrace();
Toast.makeText(UserCenter.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}
if (dialog != null) {
dialog.dismiss();
}
}
/**
* Microblog authentication authorization callback class. 1. SSO When authorization is required {@link #onActivityResult} In the call
* {@link SsoHandler#authorizeCallBack} Later, The callback is executed. 2. non SSO
* When authorization expires, the callback is executed. When the authorization is successful, save the access_token , expires_in , uid Information such as the
* SharedPreferences In the.
*/
class AuthListener implements WeiboAuthListener {
@Override
public void onComplete(Bundle values) {
//Parse Token
from the Bundle
mAccessToken = Oauth2AccessToken.parseAccessToken(values);
if (mAccessToken.isSessionValid()) {
//Save the Token to SharedPreferences
AccessTokenKeeper.writeAccessToken(UserCenter.this,
mAccessToken);
sendMessage();
}
}
@Override
public void onCancel() {
}
@Override
public void onWeiboException(WeiboException e) {
Toast.makeText(UserCenter.this,
"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
/**
* Sina weibo user authorization
*/
public void startSinaShare() {
mSsoHandler = new SsoHandler(UserCenter.this, mWeiboAuth);
//
,
,
,
,
,
,
,
mAccessToken = AccessTokenKeeper.readAccessToken(this);
//If the Token is valid, the sending tweet
is called directly
if (mAccessToken.isSessionValid()) {
sendMessage();
} else {
mSsoHandler.authorize(new AuthListener());
}
}
/**
* @See {@link Activity#onNewIntent}
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//This is where the
function needs to be called when we return to the current application after the microblog is evoked and Shared from the current application
//To receive the data returned by the microblogging client; Execute successfully, return true, and call
//< a href = "mailto: {@ the link" > {@ the link < / a > IWeiboHandler. Response# onResponse}; Failure returns false without calling the above callback
mWeiboShareAPI.handleWeiboResponse(intent, this);
}
/**
* when SSO authorization Activity When exiting, the function is called.
*
* @see {@link Activity#onActivityResult}
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//SSO authorization callback
//Important: the Activity that initiated the SSO login must override the onActivityResult
if (mSsoHandler != null) {
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
/**
* Receive data requested by microclient. This method is called when the microblogging client invokes the current application and shares it.
*
* @param baseRequest
* Weibo requests data objects
* @see {@link IWeiboShareAPI#handleWeiboRequest}
*/
@Override
public void onResponse(BaseResponse baseResp) {
switch (baseResp.errCode) {
case WBConstants.ErrorCode.ERR_OK:
if (PublicFun.shareCondition()) {
gainBoBi();
} else {
Toast.makeText(this, R.string.share_success, Toast.LENGTH_LONG)
.show();
}
break;
case WBConstants.ErrorCode.ERR_CANCEL:
break;
case WBConstants.ErrorCode.ERR_FAIL:
Toast.makeText(this, R.string.errcode_deny, Toast.LENGTH_LONG)
.show();
break;
}
if (dialog != null) {
dialog.dismiss();
}
}
/**
* A third-party application sends a request message to weibo to evoke the weibo sharing interface.
* @see {@link #sendMultiMessage} or {@link #sendSingleMessage}
*/
private void sendMessage() {
if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
sendMultiMessage();
} else {
Toast.makeText(this, R.string.sina_share_hint, Toast.LENGTH_SHORT)
.show();
}
}
/**
* A third-party application sends a request message to weibo to evoke the weibo sharing interface. Note: when
* {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351 Support for sharing multiple messages at the same time,
*
* @param hasText
* Whether the content Shared has text or not
* @param hasImage
* Whether the content Shared has pictures or not
* @param hasWebpage
* Whether the content Shared has a web page or not
*/
private void sendMultiMessage() {
//1. Initiate the sharing message of weibo
WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
weiboMessage.textObject = getTextObj();
//Users can share other media resources (web pages, music, videos, one of the sounds)
weiboMessage.mediaObject = getWebpageObj();
//2. Initializes a message request from a third party to weibo
SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
//A request
is uniquely identified by transaction
request.transaction = String.valueOf(System.currentTimeMillis());
request.multiMessage = weiboMessage;
//3. Send a request message to weibo to evoke the weibo sharing interface
mWeiboShareAPI.sendRequest(request);
//Share log
PublicFun.sendShareAppLog(UserCenter.this,
getResources().getString(R.string.micro_blog));
if (dialog != null) {
dialog.dismiss();
}
}
/**
* Create a text message object.
* @return Text message object.
*/
private TextObject getTextObj() {
TextObject textObject = new TextObject();
textObject.text = getResources().getString(R.string.share_content);
return textObject;
}
/**
* Create a multimedia (web) message object.
* @return Multimedia (web) message object.
*/
private WebpageObject getWebpageObj() {
WebpageObject mediaObject = new WebpageObject();
mediaObject.actionUrl = getString(R.string.share_url);
mediaObject.identify = Utility.generateGUID();
mediaObject.title = getResources().getString(R.string.share_title);
mediaObject.description = getString(R.string.share_content);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.icon);
mediaObject.setThumbImage(bmp);
return mediaObject;
}
/**
* This class defines the parameters needed to authorize a microblog.
* @author SINA
* @SINCE 2013-10-07
*/
public class AccessTokenKeeper {
private static final String PREFERENCES_NAME = "com_weibo_sdk_android";
private static final String KEY_UID = "uid";
private static final String KEY_ACCESS_TOKEN = "access_token";
private static final String KEY_EXPIRES_IN = "expires_in";
/**
* save Token Object to SharedPreferences .
*
* @param context Application context
* @param token Token object
*/
public static void writeAccessToken(Context context, Oauth2AccessToken token) {
if (null == context || null == token) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
Editor editor = pref.edit();
editor.putString(KEY_UID, token.getUid());
editor.putString(KEY_ACCESS_TOKEN, token.getToken());
editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
editor.commit();
}
/**
* from SharedPreferences read Token Information.
*
* @param context Application context
*
* @return return Token object
*/
public static Oauth2AccessToken readAccessToken(Context context) {
if (null == context) {
return null;
}
Oauth2AccessToken token = new Oauth2AccessToken();
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
token.setUid(pref.getString(KEY_UID, ""));
token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));
return token;
}
/**
* empty SharedPreferences In the Token Information.
*
* @param context Application context
*/
public static void clear(Context context) {
if (null == context) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
Editor editor = pref.edit();
editor.clear();
editor.commit();
}
}
All of the above is the content of this article, hope to help you master Java.