weibo.java
The code copy is as follows:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_center);
// Create a Weibo instance
mWeiboAuth = new WeiboAuth(this, Constants.APP_KEY,
Constants.REDIRECT_URL, Constants.SCOPE);
// Create a Weibo sharing interface example
mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constants.APP_KEY);
// When the Activity is reinitialized (the Activity is in the background, it may be killed due to insufficient memory),
// You need to call {@link IWeiboShareAPI#handleWeiboResponse} to receive the data returned by the Weibo client.
// Execution is successful, return true, and call {@link IWeiboHandler.Response#onResponse};
// Failure to return false, no callback above is called
if (savedInstanceState != null) {
mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
}
}
/**
* Check whether the user has installed Sina Weibo
*/
public void isNotInstall() {
try {
// Check whether the Weibo client environment is normal. If Weibo is not installed, a dialog box will pop up to ask the user to download the Weibo client
if (mWeiboShareAPI.checkEnvironment(true)) {
// Register a third-party application to the Weibo client. After the registration is successful, the application will be displayed in the Weibo application list.
// However, the integration and sharing permissions of this attachment column require cooperation application. For details, please check the demo prompts.
mWeiboShareAPI.registerApp();
startSinaShare();
}
} catch (WeiboShareException e) {
e.printStackTrace();
Toast.makeText(UserCenter.this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}
if (dialog != null) {
dialog.dismiss();
}
}
/**
* Weibo authentication and authorization callback category. 1. When authorizing SSO, you need to call it in {@link #onActivityResult}
* {@link SsoHandler#authorizeCallBack}, the callback will be executed. 2. Non-SSO
* When authorization is granted, the callback will be executed after authorization is completed. When the authorization is successful, please save the access_token, expires_in, uid and other information to
* SharedPreferences in.
*/
class AuthListener implements WeiboAuthListener {
@Override
public void onComplete(Bundle values) {
// parse the token from the Bundle
mAccessToken = Oauth2AccessToken.parseAccessToken(values);
if (mAccessToken.isSessionValid()) {
// Save 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);
// Read information such as AccessToken that was saved last time from SharedPreferences.
mAccessToken = AccessTokenKeeper.readAccessToken(this);
// If the token is valid, call and send Weibo directly
if (mAccessToken.isSessionValid()) {
sendMessage();
} else {
mSsoHandler.authorize(new AuthListener());
}
}
/**
* @See {@link Activity#onNewIntent}
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// After calling Weibo from the current application and sharing it, when returning to the current application, you need to call this function here
// To receive the data returned by the Weibo client; execute successfully, return true and call
// {@link IWeiboHandler.Response#onResponse}; Failure to return false, the above callback is not called
mWeiboShareAPI.handleWeiboResponse(intent, this);
}
/**
* When the SSO authorization Activity exits, 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 initiates the SSO login must be rewrite onActivityResult
if (mSsoHandler != null) {
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
/**
* Receive data requested by micro-client. When the Weibo client calls up the current application and shares it, the method is called.
*
* @param baseRequest
* Weibo request data object
* @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 and calls up 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 and calls up the Weibo sharing interface. Note: When
* {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351, it supports sharing multiple messages at the same time.
*
* @param hasText
* Is there any text for the shared content
* @param hasImage
* Is there any pictures shared content
* @param hasWebpage
* Is there a web page for the shared content?
*/
private void sendMultiMessage() {
// 1. Initialize the sharing message on Weibo
WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
weiboMessage.textObject = getTextObj();
// Users can share other media resources (one of web pages, music, videos, and sounds)
weiboMessage.mediaObject = getWebpageObj();
// 2. Initialize message requests from third parties to Weibo
SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
//Use transaction to uniquely identify a request
request.transaction = String.valueOf(System.currentTimeMillis());
request.multiMessage = weiboMessage;
// 3. Send a request message to Weibo and call up the Weibo sharing interface
mWeiboShareAPI.sendRequest(request);
// Record sharing 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 page) message object.
* @return Multimedia (web page) 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 required for Weibo authorization.
* @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 the 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();
}
/**
* Read Token information from SharedPreferences.
*
* @param context Application context
*
* @return Return to the 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;
}
/**
* Clear the Token information in SharedPreferences.
*
* @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();
}
}
The above is all about this article, and I hope it will be helpful for everyone to master Java.