仿新浪微博2014之登陆界面四(总体功能)

zz/2024/7/24 1:41:51

在前面完成了数据库操作、异步图片加载和缓存、新浪微博认证后,就可以进行登录界面的功能开发了,登录界面功能代码如下:

package com.xhq.xweibo.ui;import java.util.ArrayList;
import java.util.List;import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.net.AsyncWeiboRunner;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.net.WeiboParameters;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.sina.weibo.sdk.openapi.models.User;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.LogUtil;
import com.sina.weibo.sdk.utils.UIUtils;import com.xhq.common.AsyncImageLoader;
import com.xhq.common.ImageUtil;
import com.xhq.common.NetUtil;
import com.xhq.xweibo.logic.Constants;
import com.xhq.xweibo.logic.CurUserKeeper;
import com.xhq.xweibo.logic.UserInfo;
import com.xhq.xweibo.logic.XDBHelper;
import com.xhq.xweibo.R;import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;public class LoginActivity extends Activity
{private static final String TAG = "LoginActivity";private static final String WEIBO_DEMO_APP_SECRET = "4e47e691a516afad0fc490e05ff70ee5";private static final String OAUTH2_ACCESS_TOKEN_URL = "https://open.weibo.cn/oauth2/access_token";// UI references.private static ImageView mHeaderView;private static Spinner mAccountView;private static Button mLoginBotton;private static Button mAuthBotton;private static Button mExitBotton;private static Button mLogoutBotton;private static ProgressDialog pd;private static XDBHelper mDBHelper;private static List<UserInfo> mUserList;private static UserInfo mCurUser;private ArrayAdapter<String> mAdapter;private List<String> mUserNameList;private static long m_nExitTime;private AsyncImageLoader  mImageLoader;private AsyncImageLoader.onLoadCompleteListener mLoadCompleteListener;private WeiboAuth mWeiboAuth;private String mCode;private Oauth2AccessToken mAccessToken;private UsersAPI mUsersAPI;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);//this.requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_login);// Set up the login form.mHeaderView = (ImageView) findViewById(R.id.login_header);mAccountView = (Spinner) findViewById(R.id.login_account);mLoginBotton = (Button) findViewById(R.id.login_button);mAuthBotton = (Button) findViewById(R.id.login_auth);mExitBotton = (Button) findViewById(R.id.login_exit);mLogoutBotton = (Button) findViewById(R.id.login_logout);mImageLoader = new AsyncImageLoader(this.getApplicationContext());mDBHelper = new XDBHelper(LoginActivity.this);mUserNameList = new ArrayList<String>();mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mUserNameList);initUser();mLoginBotton.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){CharSequence error;if (mUserList.isEmpty()){error = getString(R.string.login_error_noneaccount);Toast.makeText(LoginActivity.this, error, Toast.LENGTH_LONG).show();} else{if (mCurUser != null){	pd = new ProgressDialog(LoginActivity.this);pd.setMessage("登录服务器....");pd.show();CurUserKeeper.saveCurUser(getApplicationContext(), mCurUser);Intent it = new Intent();it.setClass(LoginActivity.this, TabHostActivity.class);startActivity(it);pd.dismiss();finish();}else{Toast.makeText(getApplicationContext(), "无用户账号", Toast.LENGTH_SHORT).show();}}}});mAuthBotton.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){mWeiboAuth = new WeiboAuth(LoginActivity.this,Constants.APP_KEY, Constants.REDIRECT_URL,Constants.SCOPE);mWeiboAuth.authorize(new AuthListener(),WeiboAuth.OBTAIN_AUTH_CODE);}});mExitBotton.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){// TODO 自动生成的方法存根finish();System.exit(0);}});mLogoutBotton.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){}});}@Overrideprotected void onResume(){// TODO Auto-generated method stubsuper.onResume();init();}public boolean onKeyDown(int keyCode, KeyEvent event){if (keyCode == KeyEvent.KEYCODE_BACK&& event.getAction() == KeyEvent.ACTION_DOWN){if ((System.currentTimeMillis() - m_nExitTime) > 2000) //{Toast.makeText(getApplicationContext(), "再按一次退出程序",Toast.LENGTH_SHORT).show();m_nExitTime = System.currentTimeMillis();} else{finish();System.exit(0);}return true;}return super.onKeyDown(keyCode, event);}public void initUser(){Log.d(TAG, "initUser");mDBHelper.createUserTable();mUserList = mDBHelper.getUserList(false);if (!mUserList.isEmpty()){// 获取用户名列表,并关联到spinner控件for (UserInfo ui : mUserList){mUserNameList.add(ui.getUserName());}mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);mAccountView.setAdapter(mAdapter);mAccountView.setOnItemSelectedListener(new SpinnerSelectedListener());// 获取最近登录的用户SharedPreferences sp = getSharedPreferences("lastUser",Activity.MODE_PRIVATE);String name = sp.getString("lastUser", "");if (name != ""){mAccountView.setSelection(mUserNameList.indexOf(name), true);} else{mAccountView.setSelection(0, true);}} else{Log.d(TAG, "Have 0 user");}}public void init(){Log.d(TAG, "init");Intent it = new Intent("com.xhq.xweibo.logic.XService");startService(it);}public void fetchTokenAsync(String authCode, String appSecret){WeiboParameters requestParams = new WeiboParameters();requestParams.put(WBConstants.AUTH_PARAMS_CLIENT_ID, Constants.APP_KEY);requestParams.put(WBConstants.AUTH_PARAMS_CLIENT_SECRET, appSecret);requestParams.put(WBConstants.AUTH_PARAMS_GRANT_TYPE,"authorization_code");requestParams.put(WBConstants.AUTH_PARAMS_CODE, authCode);requestParams.put(WBConstants.AUTH_PARAMS_REDIRECT_URL,Constants.REDIRECT_URL);// 异步请求,获取 TokenAsyncWeiboRunner.requestAsync(OAUTH2_ACCESS_TOKEN_URL, requestParams,"POST", new RequestListener(){@Overridepublic void onComplete(String response){LogUtil.d(TAG, "Response: " + response);Oauth2AccessToken token = Oauth2AccessToken.parseAccessToken(response);if (token != null && token.isSessionValid()){LogUtil.d(TAG, "Success! " + token.toString());mCurUser = new UserInfo();mAccessToken = token;mCurUser.setUserId(mAccessToken.getUid());mCurUser.setToken(mAccessToken.getToken());mCurUser.setUserExpiresin(mAccessToken.getExpiresTime());mUsersAPI = new UsersAPI(mAccessToken);long uid = Long.parseLong(mAccessToken.getUid());mUsersAPI.show(uid, mListener);} else{LogUtil.d(TAG, "Failed to receive access token");}}@Overridepublic void onWeiboException(WeiboException e){LogUtil.e(TAG, "onWeiboException: " + e.getMessage());Toast.makeText(LoginActivity.this, "获取Token失败",Toast.LENGTH_SHORT).show();}});}/*** 微博 OpenAPI 回调接口。*/private RequestListener mListener = new RequestListener(){@Overridepublic void onComplete(String response){if (!TextUtils.isEmpty(response)){LogUtil.i(TAG, response);User user = User.parse(response);if (user != null){LogUtil.d(TAG, "Success to get screen_name: "+ user.screen_name);mCurUser.setUserName(user.screen_name);mCurUser.setUserIcon(user.profile_image_url);					mDBHelper.SaveUserInfo(mCurUser);initUser();mImageLoader.loadImage(mHeaderView,user.profile_image_url, mLoadCompleteListener);} else{Toast.makeText(LoginActivity.this, response,Toast.LENGTH_LONG).show();}}}@Overridepublic void onWeiboException(WeiboException e){LogUtil.e(TAG, e.getMessage());}};class SpinnerSelectedListener implements OnItemSelectedListener{public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3){Log.d("LoginActivity", "spinner item selected");mCurUser = mDBHelper.getUserByName(mUserNameList.get(arg2),mUserList);if (null != mCurUser){mImageLoader.loadImage(mHeaderView,mCurUser.getUserIcon(), new AsyncImageLoader.onLoadCompleteListener(){@Overridepublic void onLoadSuccess(View view, Bitmap bmp, String url){// TODO 自动生成的方法存根((ImageView)view).setImageDrawable(ImageUtil.BMP2Drawable(bmp));}@Overridepublic void onLaodFail(View view, String url){// TODO 自动生成的方法存根((ImageView)view).setImageResource(R.drawable.login_user_ic);}});}}public void onNothingSelected(AdapterView<?> arg0){}}class AuthListener implements WeiboAuthListener{@Overridepublic void onComplete(Bundle values){if (null == values){Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();return;}String code = values.getString("code");if (TextUtils.isEmpty(code)){Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();return;}LogUtil.d(TAG, "Success to get code");mCode = code;fetchTokenAsync(mCode, WEIBO_DEMO_APP_SECRET);}@Overridepublic void onCancel(){Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_LONG).show();}@Overridepublic void onWeiboException(WeiboException e){UIUtils.showToast(LoginActivity.this,"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG);}}}

主要逻辑如下:

(1)初始化:登录界面载入时,先到数据库中取出用户列表,把用户名加入到Spinner中,然后通过 SharedPreferences 获取最近登录过的用户,

                        SharedPreferences sp = getSharedPreferences("lastUser",Activity.MODE_PRIVATE);
                        String name = sp.getString("lastUser", "");

                        然后让Spinner选中相应的用户,然后在SpinnerSelectedListener  中保存获取当前用户信息,异步加载用户头像。
(2)添加授权: 点击添加授权按钮后,就进入授权界面了,获取到code后,再获取token,然后保存用户的相应信息到数据库,然后把当前用户选择为刚刚授权成功的账号。

(3)退出  :点击退出按钮直接退出程序或者在2秒内点击返回键。

(4)注销账号:功能还没实现。

(5)登录 :点击登录按钮后就会进入到微博的主界面了。


http://www.ngui.cc/zz/2390150.html

相关文章

发一个文件读写类

<?php /* * author:xhq * email:xhq6632126.com * QQ:119948717 */ header("Content-type: text/html; charsetutf-8");class filesystem {/*名称&#xff1a;创建文件参数&#xff1a;文件名&#xff0c;写入的数据&#xff0c;模式*/function writefile($file,…

2021北京高考英语口试成绩查询,2021北京高考英语增加口试

依据北京推进高等院校考试招生规章制度综合性改革创新实施意见&#xff0c;从二零二一年起&#xff0c;英文提升口语考试&#xff0c;英语口语加听力考试总共50分&#xff0c;听闻无纸化考试2020年将首考。高考英语提升口语这针对关心今年高考的父母而言&#xff0c;很有可能并…

Java程序员面试必备的20道数据库面试解析

进了互联网公司&#xff0c;整天也就是搬砖&#xff0c;等到了面试的时候&#xff0c;发现数据库方面&#xff0c;忘得一塌糊涂&#xff0c;抽时间整理了一些数据库方面的题。进了互联网公司&#xff0c;整天也就是搬砖&#xff0c;等到了面试的时候&#xff0c;发现数据库方面…

2022最新数据库面试题大全

一、基本概念 1.主键、外键、超键、候选键 超键&#xff1a;在关系中能唯一标识元组的属性集称为关系模式的超键。一个属性可以为作为一个超键&#xff0c;多个属性组合在一起也可以作为一个超键。超键包含候选键和主键。 候选键&#xff1a;是最小超键&#xff0c;即没有冗余…

python发音机器人_Python3从零开始搭建一个语音对话机器人

目录 01-初心缘由 最近在研究语音识别方向&#xff0c;看了很多的语音识别的资料和文章&#xff0c;了解了一下语音识别的前世今生&#xff0c;其中包含了很多算法的演变&#xff0c;目前来说最流行的语音识别算法主要是依赖于深度学习的神经网络算法&#xff0c;其中RNN扮演了…

赞一下老北京人的指路精准度

昨晚下班没事&#xff0c;网上查好公交往返路线&#xff0c;就坐公交去了趟前门大栅栏逛了逛。无意间感受到了老北京人的热情及指路的精准度。 虽在北京这么多年&#xff0c;但这个大栅栏还真没去过。特11到大栅栏&#xff0c;听公交报站&#xff0c;才知道这发音叫大栅…

新妈妈北京求职之路

我是一名孩子不满半岁的年轻妈妈。为了生活我毅然重返职场。发现在职场上与我情况相似的妈妈们非常多。那么&#xff0c;像我们这样的新妈妈在应聘中会遇到什么样的问题呢&#xff1f;我的这篇博文就是以记者采访的手法&#xff0c;记录了我应聘一家私立学校的前前后后。希望能…

程序员在北京找工作的感悟

一个程序员在北京找工作的感悟-很有感觉 2017年07月12日 14:47:17 p312011150 阅读数&#xff1a;9748 一个程序员在北京找工作的感悟-很有感觉 这是一个人的真实面试经历&#xff0c;在北京&#xff0c;东直门、知春路、建外SOHO&#xff0c;但凡参加过工作的人都知道&#…

北京中医药大学计算机应用基础作业,北京中医药大学网络教育高起点语文入学考试模拟题(单选一)...

远程教育学院《语文》入学考试辅导资料---仅适用于专科、本科层次(高中或中专起点)一、A型题&#xff1a;1.在“邻国之民不加少&#xff0c;寡人之民不加多&#xff0c;何也”中&#xff0c;“加”之义是&#xff1a;A.增 B.减 C.更 D.又2.在“填然鼓之&#xff0c;兵刃既接&am…

一个游戏社交产品

现在朋友圈也好&#xff0c;QQ空间也好&#xff0c;都充斥着大量不想看到的信息&#xff0c;新浪微博更是让人没有打开的欲望。这其中的无聊的内容主要分两种&#xff1a;一种是来自偶尔发有用信息的无聊的人&#xff0c;比如一些公共号&#xff1b;另外一种是有趣的人偶尔发的…