private void updateTokenView(boolean hasExisted) { String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss") .format(new java.util.Date(mAccessToken.getExpiresTime())); String format = context.getString(R.string.weibosdk_demo_token_to_string_format_1); String message = String.format(format, mAccessToken.getToken(), date); }
/** * 当前用户 * * @param context context */ public static void start(Context context) { Intent intent = new Intent(context, UserDetailActivity.class); Oauth2AccessToken token = AccessTokenKeeper.readAccessToken(context); intent.putExtra(INTENT_UID, token.getUid()); intent.putExtra(INTENT_TOKEN, token.getToken()); context.startActivity(intent); }
private void refreshTokenRequest() { Oauth2AccessToken token = AccessTokenKeeper.readAccessToken(WBOpenAPIActivity.this); RefreshTokenApi.create(getApplicationContext()) .refreshToken( Constants.APP_KEY, token.getRefreshToken(), new RequestListener() { @Override public void onWeiboException(WeiboException arg0) { Toast.makeText( WBOpenAPIActivity.this, "RefreshToken Result : " + arg0.getMessage(), Toast.LENGTH_LONG) .show(); } @Override public void onComplete(String arg0) { Toast.makeText( WBOpenAPIActivity.this, "RefreshToken Result : " + arg0, Toast.LENGTH_LONG) .show(); } }); }
/** * 保存 Token 对象到 SharedPreferences。 * * @param context 应用程序上下文环境 * @param token Token 对象 */ 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(); }
/** * 从 SharedPreferences 读取 Token 信息。 * * @param context 应用程序上下文环境 * @return 返回 Token 对象 */ 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; }
public void logoutWB() { // 获取当前已保存过的 Token mAccessToken = AccessTokenKeeper.readAccessToken(this); if (mAccessToken != null && mAccessToken.isSessionValid()) { String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss") .format(new java.util.Date(mAccessToken.getExpiresTime())); } // 注销按钮 if (mAccessToken != null && mAccessToken.isSessionValid()) { new LogoutAPI(SetActivity.this, WBConstants.APP_KEY, mAccessToken) .logout(mLogoutRequestListener); } else { // Toasts.show(SetActivity.this, "注销失败,请检查 Token 是否正确(一个 token 不能重复注销多次)", 0); } }
@Override public void onComplete(Bundle values) { // 从 Bundle 中解析 Token mAccessToken = Oauth2AccessToken.parseAccessToken(values); // 从这里获取用户输入的 电话号码信息 String phoneNum = mAccessToken.getPhoneNum(); if (mAccessToken.isSessionValid()) { // 显示 Token TextView tv = (TextView) findViewById(R.id.token); tv.setText("Token:\n" + mAccessToken.getToken()); String uid = mAccessToken.getUid(); showUsrInfo(uid, mAccessToken.getToken()); Toast.makeText(MainActivity.this, "auth_success", Toast.LENGTH_SHORT).show(); } else { // 以下几种情况,您会收到 Code: // 1. 当您未在平台上注册的应用程序的包名与签名时; // 2. 当您注册的应用程序包名与签名不正确时; // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。 String code = values.getString("code"); String message = "weibosdk auth_failed"; if (!TextUtils.isEmpty(code)) { message = message + "\nObtained the code: " + code; } Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show(); } }
@Override public void onComplete(Bundle values) { // 从 Bundle 中解析 Token mAccessToken = Oauth2AccessToken.parseAccessToken(values); // 从这里获取用户输入的 电话号码信息 String phoneNum = mAccessToken.getPhoneNum(); if (mAccessToken.isSessionValid()) { // 保存 Token 到 SharedPreferences AccessTokenKeeper.writeAccessToken(WelcomActivity.this, mAccessToken); Toast.makeText( WelcomActivity.this, R.string.weibosdk_demo_toast_auth_success, Toast.LENGTH_SHORT) .show(); startActivity(new Intent(WelcomActivity.this, MainActivity.class)); WelcomActivity.this.finish(); } else { // 以下几种情况,您会收到 Code: // 1. 当您未在平台上注册的应用程序的包名与签名时; // 2. 当您注册的应用程序包名与签名不正确时; // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。 String code = values.getString("code"); String message = getString(R.string.weibosdk_demo_toast_auth_failed); if (!TextUtils.isEmpty(code)) { message = message + "\nObtained the code: " + code; } Toast.makeText(WelcomActivity.this, message, Toast.LENGTH_LONG).show(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcom); Oauth2AccessToken oauth2AccessToken = AccessTokenKeeper.readAccessToken(this); if (oauth2AccessToken != null && !TextUtils.isEmpty(oauth2AccessToken.getUid()) && !TextUtils.isEmpty(oauth2AccessToken.getToken()) && !TextUtils.isEmpty(oauth2AccessToken.getRefreshToken())) { startActivity(new Intent(this, MainActivity.class)); this.finish(); } else { mAuthInfo = new AuthInfo(this, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE); mSsoHandler = new SsoHandler(WelcomActivity.this, mAuthInfo); mSsoHandler.authorize(new AuthListener()); } }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.ibtn_refresh_activity_friend: users_list.clear(); mFriendshipsAPI.followers( Long.parseLong(mAccessToken.getUid()), 200, 0, false, new MyRequestListener()); break; case R.id.ibtn_return_activity_friend: finish(); break; } }
/** * 发送微博 * * @param token * @param editText * @return */ public static Boolean sendWeibo(Oauth2AccessToken token, EditText editText, byte[] imgBuffer) { HttpPost postMethod; // 组织post参数:此处只实现最简单的发送消息,只填两个参数,其他见http://open.weibo.com/wiki/2/statuses/friends_timeline HttpClient httpClient = new DefaultHttpClient(); List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); String messageString = editText.getText().toString(); params.add(new BasicNameValuePair("status", messageString)); params.add(new BasicNameValuePair("access_token", token.getToken())); // 判断是否有图片,选择不同的接口 if (null != imgBuffer) { Log.w(TAG, "Image file include!"); params.add(new BasicNameValuePair("pic", imgBuffer.toString())); postMethod = new HttpPost(Contants.STATUESES_UPDATA_WITH_IMG_URL); } else { Log.w(TAG, "No images select!"); postMethod = new HttpPost(Contants.STATUESES_UPDATA_URL); } try { postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); HttpResponse httpResponse = httpClient.execute(postMethod); // 将返回结果转为字符串,通过文档可知返回结果为json字符串,结构请参考文档 String resultStr = EntityUtils.toString(httpResponse.getEntity()); Log.w(TAG, resultStr); // 从json字符串中建立JSONObject JSONObject resultJson = new JSONObject(resultStr); // 如果发送微博失败的话,返回字段中有"error"字段,通过判断是否存在该字段即可知道是否发送成功 if (resultJson.has("error")) { return false; } else { return true; } } catch (UnsupportedEncodingException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ClientProtocolException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ParseException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.w(TAG, e.getLocalizedMessage()); } return false; }
@Override public void onComplete(Bundle values) { mAccessToken = Oauth2AccessToken.parseAccessToken(values); if (mAccessToken.isSessionValid()) { mShareCalls.onAuthListener(mAccessToken); AccessTokenKeeper.writeAccessToken(context, mAccessToken); } else { mShareCalls.onAuthListener(null); String code = values.getString("code"); String message = ""; if (!TextUtils.isEmpty(code)) { message = message + "\nObtained the code: " + code; } } }
@Override public void onComplete(Bundle values) { weiboAccessToken = Oauth2AccessToken.parseAccessToken(values); if (weiboAccessToken.isSessionValid()) { AccessTokenKeeper.writeAccessToken(Login.this, weiboAccessToken); getWeiboUserInfo(); } else { String code = values.getString("code"); String message = getString(R.string.dialog_login_result_err_weibo); if (!TextUtils.isEmpty(code)) { message = message + "\nCode: " + code; } Utils.Dialog(Login.this, getString(R.string.dialog_normal_title), message); } }
private void init() { imageLoader = ImageLoader.getInstance(); imageLoader.init(ImageLoader_Init_Util.initConfiguration(getApplicationContext())); circleOptions = ImageLoader_Init_Util.initCircleDisplayImageOption(getApplicationContext()); inflater = LayoutInflater.from(getApplicationContext()); mFriendsAdapter = new FriendsAdapter(inflater, users_list, imageLoader, circleOptions); mAccessToken = AccessTokenKeeper.readAccessToken(getApplicationContext()); mFriendshipsAPI = new FriendshipsAPI(getApplicationContext(), Constants.APP_KEY, mAccessToken); ibtn_refresh = (ImageButton) findViewById(R.id.ibtn_refresh_activity_friend); ibtn_return = (ImageButton) findViewById(R.id.ibtn_return_activity_friend); tv_title = (TextView) findViewById(R.id.tv_title_activity_friend); tv_title.setText("我的粉丝"); lv_followers = (ListView) findViewById(R.id.lv_friends_activity_friend); lv_followers.setAdapter(mFriendsAdapter); mFriendshipsAPI.followers( Long.parseLong(mAccessToken.getUid()), 200, 0, false, new MyRequestListener()); }
/** * 查询accesstoken是否过期 * * @param context * @param token * @return */ public static Boolean isTokenOverTime(Context context, Oauth2AccessToken token) { // 组织post参数:此处只实现最简单的发送消息,只填两个参数,其他见http://open.weibo.com/wiki/2/statuses/friends_timeline List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("access_token", token.getToken())); try { JSONObject resultJSON = doPost(context, params, Contants.GET_TOKEN_INFO_URL); try { String timeRest = resultJSON.getString("expire_in"); Log.w(TAG, "Token rest time :" + timeRest); long time = Integer.parseInt(timeRest); if (time < 1000) { return false; } } catch (JSONException e) { e.printStackTrace(); } } catch (Exception e) { } return true; }
public static long getCurrentUserId(Oauth2AccessToken token) { JSONObject resultJson = null; HttpResponse httpResponse; HttpClient httpClient = new DefaultHttpClient(); // 传入get方法的请求地址和参数 HttpGet getMethod = new HttpGet(Contants.GET_CURRENT_USER_INFO_URL + "?" + "access_token=" + token.getToken()); try { // execute返回一个响应对象 httpResponse = httpClient.execute(getMethod); // 响应的内容对象 // 读取内容,用inputstream读取 String resultStr = EntityUtils.toString(httpResponse.getEntity()); resultJson = new JSONObject(resultStr); // 如果发送微博失败的话,返回字段中有"error"字段,通过判断是否存在该字段即可知道是否发送成功 if (resultJson.has("error")) { Log.w(TAG, "获取用户信息失败"); } // Log.i(TAG, resultJson.toString()); } catch (UnsupportedEncodingException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ClientProtocolException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ParseException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.w(TAG, e.getLocalizedMessage()); } try { return resultJson.getLong("uid"); } catch (JSONException e) { e.printStackTrace(); } return 0; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forward_comment); cid = getIntent().getStringExtra("cid"); id = getIntent().getStringExtra("id"); if (TextUtils.isEmpty(cid) || TextUtils.isEmpty(id)) { finish(); return; } mAccessToken = AccessTokenKeeper.readAccessToken(getApplicationContext()); mParams = new WeiboParameters(Constants.APP_KEY); mParams.put("access_token", mAccessToken.getToken()); inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); titleBar = (TitleBar) findViewById(R.id.title_bar); replyContent = (EditText) findViewById(R.id.et_forward_content); countTV = (TextView) findViewById(R.id.tv_count); sameTime = (CheckBox) findViewById(R.id.cb_same_time); faceKeyboard = (ImageButton) findViewById(R.id.btn_face_keyboard); send = (ImageButton) findViewById(R.id.btn_send); faceGrid = (GridView) findViewById(R.id.gv_face); inputRoot = (RelativeLayout) findViewById(R.id.ll_input_root); sameTime.setVisibility(View.GONE); titleBar.setTitle("回复"); titleBar.setBackClickListener(this); replyContent.setHint("回复"); replyContent.addTextChangedListener(this); replyContent.setSelection(0); replyContent.setOnClickListener(this); faceKeyboard.setOnClickListener(this); faceGrid.setAdapter(new EmotionsGridAdapter(this)); faceGrid.setOnItemClickListener(this); send.setOnClickListener(this); inputRoot.setOnClickListener(this); }
/** * 获取所有新消息数,UID为当前登陆用户 * * @return */ public static NewMsg getNewMessageCounts(Oauth2AccessToken token, Long currentUID) { NewMsg newMsg = new NewMsg(); JSONObject resultJson = null; HttpResponse httpResponse; HttpClient httpClient = new DefaultHttpClient(); // 传入get方法的请求地址和参数 HttpGet getMethod = new HttpGet( Contants.GET_MESSAGE_COUNT_URL + "?" + "access_token=" + token.getToken() + "&true=" + currentUID); try { // execute返回一个响应对象 httpResponse = httpClient.execute(getMethod); // 响应的内容对象 // 读取内容,用inputstream读取 String resultStr = EntityUtils.toString(httpResponse.getEntity()); resultJson = new JSONObject(resultStr); // 如果发送微博失败的话,返回字段中有"error"字段,通过判断是否存在该字段即可知道是否发送成功 if (resultJson.has("error")) { Log.w(TAG, "获取用户信息失败"); } // Log.i(TAG, resultJson.toString()); } catch (UnsupportedEncodingException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ClientProtocolException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ParseException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.w(TAG, e.getLocalizedMessage()); } // 保存消息数 try { newMsg.setStatus(resultJson.getInt("status")); } catch (Exception e) { } try { newMsg.setFollower(resultJson.getInt("follower")); } catch (Exception e) { } try { newMsg.setCmt(resultJson.getInt("cmt")); } catch (Exception e) { } try { newMsg.setDm(resultJson.getInt("dm")); } catch (Exception e) { } try { newMsg.setMention(resultJson.getInt("mention_status") + resultJson.getInt("mention_cmt")); } catch (Exception e) { } return newMsg; }
public class SsoHandler { private static final String DEFAULT_SINA_WEIBO_PACKAGE_NAME = "com.sina.weibo"; private static final String DEFAULT_WEIBO_REMOTE_SSO_SERVICE_NAME = "com.sina.weibo.remotessoservice"; private static final int REQUEST_CODE_SSO_AUTH = 32973; private static final String TAG = "Weibo_SSO_login"; private Activity mAuthActivity; private WeiboAuthListener mAuthListener; private ServiceConnection mConnection; private int mSSOAuthRequestCode; private WeiboAuth mWeibo; public SsoHandler(Activity activity, WeiboAuth weiboauth) { mConnection = new _cls1(); mAuthActivity = activity; mWeibo = weiboauth; } private boolean bindRemoteSSOService(Context context, String s) { boolean flag = true; if (TextUtils.isEmpty(s) || s.trim().equals("")) { s = "com.sina.weibo"; } Intent intent = new Intent("com.sina.weibo.remotessoservice"); intent.setPackage(s); if (!context.bindService(intent, mConnection, flag)) { flag = context.bindService(new Intent("com.sina.weibo.remotessoservice"), mConnection, flag); } return flag; } public static ComponentName isServiceExisted(Context context, String s) { Iterator iterator = ((ActivityManager)context.getSystemService("activity")).getRunningServices(0x7fffffff).iterator(); ComponentName componentname; do { if (!iterator.hasNext()) { return null; } componentname = ((android.app.ActivityManager.RunningServiceInfo)iterator.next()).service; } while (!componentname.getPackageName().equals(s) || !componentname.getClassName().equals((new StringBuilder(String.valueOf(s))).append(".business.RemoteSSOService").toString())); return componentname; } private boolean startSingleSignOn(String s, String s1) { boolean flag = true; Intent intent = new Intent(); intent.setClassName(s, s1); intent.putExtras(mWeibo.getAuthInfo().getAuthBundle()); intent.putExtra("_weibo_command_type", 3); intent.putExtra("_weibo_transaction", String.valueOf(System.currentTimeMillis())); if (!SecurityHelper.validateAppSignatureForIntent(mAuthActivity, intent)) { return false; } try { mAuthActivity.startActivityForResult(intent, mSSOAuthRequestCode); } catch (ActivityNotFoundException activitynotfoundexception) { flag = false; } mAuthActivity.getApplicationContext().unbindService(mConnection); return flag; } public void authorize(int i, WeiboAuthListener weiboauthlistener, String s) { mSSOAuthRequestCode = i; mAuthListener = weiboauthlistener; if (!bindRemoteSSOService(mAuthActivity.getApplicationContext(), s) && mWeibo != null) { mWeibo.anthorize(mAuthListener); } } public void authorize(WeiboAuthListener weiboauthlistener) { authorize(32973, weiboauthlistener, null); } public void authorize(WeiboAuthListener weiboauthlistener, String s) { authorize(32973, weiboauthlistener, s); } public void authorizeCallBack(int i, int j, Intent intent) { if (i != mSSOAuthRequestCode) goto _L2; else goto _L1 _L1: if (j != -1) goto _L4; else goto _L3 _L3: if (SecurityHelper.checkResponseAppLegal(mAuthActivity, intent)) goto _L5; else goto _L2 _L2: return; _L5: String s = intent.getStringExtra("error"); if (s == null) { s = intent.getStringExtra("error_type"); } if (s != null) { if (s.equals("access_denied") || s.equals("OAuthAccessDeniedException")) { LogUtil.d("Weibo_SSO_login", "Login canceled by user."); mAuthListener.onCancel(); return; } String s1 = intent.getStringExtra("error_description"); if (s1 != null) { s = (new StringBuilder(String.valueOf(s))).append(":").append(s1).toString(); } LogUtil.d("Weibo_SSO_login", (new StringBuilder("Login failed: ")).append(s).toString()); mAuthListener.onWeiboException(new WeiboDialogException(s, j, s1)); return; } android.os.Bundle bundle = intent.getExtras(); Oauth2AccessToken oauth2accesstoken = Oauth2AccessToken.parseAccessToken(bundle); if (oauth2accesstoken != null && oauth2accesstoken.isSessionValid()) { LogUtil.d("Weibo_SSO_login", (new StringBuilder("Login Success! ")).append(oauth2accesstoken.toString()).toString()); mAuthListener.onComplete(bundle); return; } else { LogUtil.d("Weibo_SSO_login", "Failed to receive access token by SSO"); mWeibo.anthorize(mAuthListener); return; } _L4: if (j == 0) { if (intent != null) { LogUtil.d("Weibo_SSO_login", (new StringBuilder("Login failed: ")).append(intent.getStringExtra("error")).toString()); mAuthListener.onWeiboException(new WeiboDialogException(intent.getStringExtra("error"), intent.getIntExtra("error_code", -1), intent.getStringExtra("failing_url"))); return; } else { LogUtil.d("Weibo_SSO_login", "Login canceled by user."); mAuthListener.onCancel(); return; } } if (true) goto _L2; else goto _L6 _L6: }
if (oauth2accesstoken != null && oauth2accesstoken.isSessionValid()) { LogUtil.d("Weibo_SSO_login", (new StringBuilder("Login Success! ")).append(oauth2accesstoken.toString()).toString()); mAuthListener.onComplete(bundle); return; } else