欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android腾讯微博客户端开发三:多账号管理的实现

程序员文章站 2022-03-02 23:04:56
...
先看看效果。。Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 
列表中的账号是保存在sqlite数据库中的,下方的大图片是显示你选择的默认账号,双击图片就会显示此账号的主页

Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 

Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 

Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 


点击添加账号,将会跳向腾讯的授权页面,这个页面我是放在WebView中的,当授权成功后,腾讯的API将会返回给我们一个验证码,然后返回到我们的账号管理界面。


Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 
public class AccountActivity extends ListActivity implements OnItemClickListener,OnItemLongClickListener,OnClickListener{
	
	private final static String TAG="AccountActivity";
	private DataHelper dataHelper;
	private MyWeiboSync weibo;
	private List<UserInfo> userList;
	private ListView listView;
	private ImageView user_default_headicon;
	private LinearLayout account_add_btn_bar;
	private UserInfo currentUser;
	private UserAdapater adapater;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account);
		
		setUpViews();//设置view
		setUpListeners();//设置listenter
		
		registerReceiver(broadcastReceiver, new IntentFilter("com.weibo.caigang.getverifier"));//注册拿到验证码广播接收器.
		
		dataHelper = DataBaseContext.getInstance(getApplicationContext());//获取数据库连接类,用了单例,保证全局只有一个此对象。
		userList = dataHelper.GetUserList(false);
		
		SharedPreferences preferences = getSharedPreferences("default_user",Activity.MODE_PRIVATE);
		String nick = preferences.getString("user_default_nick", "");//取得微博默认登录账号信息
		
		UserInfo user = null;
		
		if(userList!=null&&userList.size()>0){
			if (nick != "") {
				user = dataHelper.getUserByName(nick,userList);//取得微博默认登录账号信息
			}
			if(user == null) {
				user = userList.get(0);
			}
		}
		if(user!=null){
			user_default_headicon.setImageDrawable(user.getUserIcon());
		}
		
		if(userList!=null&&userList.size()>0){
			adapater = new UserAdapater();
			listView.setAdapter(adapater);
			listView.setOnItemClickListener(this);
		}
	}
	
	private void setUpViews(){
		listView = getListView();
		user_default_headicon = (ImageView)findViewById(R.id.user_default_headicon);
		account_add_btn_bar = (LinearLayout)findViewById(R.id.account_add_btn_bar);
	}
	
	private void setUpListeners(){
		user_default_headicon.setOnClickListener(this);
		account_add_btn_bar.setOnClickListener(this);
		listView.setOnItemLongClickListener(this);
	}
	
	
	
	public class UserAdapater extends BaseAdapter{
        @Override
        public int getCount() {
            return userList.size();
        }

        @Override
        public Object getItem(int position) {
            return userList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.account_list_item, null);
			ImageView user_headicon = (ImageView) convertView.findViewById(R.id.user_headicon);
			TextView user_nick = (TextView) convertView.findViewById(R.id.user_nick);
			TextView user_name = (TextView) convertView.findViewById(R.id.user_name);
			UserInfo user = userList.get(position);
			try {
				user_headicon.setImageDrawable(user.getUserIcon());
				user_nick.setText(user.getUserName());
				user_name.setText("@"+user.getUserId());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		currentUser = userList.get(position);
		user_default_headicon.setImageDrawable(currentUser.getUserIcon());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.account_add_btn_bar: {
			weibo = WeiboContext.getInstance();//单例,保证整个应用只有一个weibo对象
			weibo.getRequestToken();
			Intent intent = new Intent(AccountActivity.this,AuthorizeActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("url", weibo.getAuthorizeUrl());
			intent.putExtras(bundle);
			startActivity(intent);//跳转到腾讯的微博授权页面,使用webview来显示
		}
			break;
		case R.id.user_default_headicon: {
			SharedPreferences preferences = getSharedPreferences("default_user", Activity.MODE_PRIVATE);
			SharedPreferences.Editor editor = preferences.edit();
			editor.putString("user_default_nick", currentUser.getUserName());
			editor.putString("user_default_name", currentUser.getUserId());
			editor.commit();
			Intent intent = new Intent(AccountActivity.this, MainActivity.class);
			startActivity(intent);
		}
			break;

		default:
			break;
		}
	}
	
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals("com.weibo.caigang.getverifier")){
				weibo = WeiboContext.getInstance();
				Bundle bundle = intent.getExtras();
				String veryfier = bundle.getString("veryfier");//获取从授权页面返回的veryfier
				if(veryfier!=null){
					//unregisterReceiver(broadcastReceiver);
					weibo.getAccessToken(weibo.getTokenKey(), weibo.getTokenSecrect(), veryfier);//取得key和secret,这个key和secret非常重要,调腾讯的API全靠它了,神马新浪的,人人网的都一样的,不过还是有点区别,腾讯的OAuth认证是基于1.0的
					String userInfo = weibo.getUserInfo(weibo.getAccessTokenKey(), weibo.getAccessTokenSecrect());
					try {
						JSONObject data = new JSONObject(userInfo).getJSONObject("data");
						String headUrl = null;
						if(data.getString("head")!=null&&!"".equals(data.getString("head"))){
							headUrl = data.getString("head")+"/100";
						}
						String userId = data.getString("name");
						String userName = data.getString("nick");
						
						UserInfo user = new UserInfo();//生成一个user对象保存到数据库
						user.setUserId(userId);
						user.setUserName(userName);
						user.setToken(weibo.getAccessTokenKey());
						user.setTokenSecret(weibo.getAccessTokenSecrect());
						
						Long insertId = 0L;
						
						if (dataHelper.HaveUserInfo(userId)){//数据库已经存在了次用户
							dataHelper.UpdateUserInfo(userName, ImageUtil.getRoundBitmapFromUrl(headUrl, 15), userId);
							//Toast.makeText(AccountActivity.this, "此用户已存在,如果你用户名或者头像已经改变,那么此操作将同步更新!", Toast.LENGTH_LONG).show();
						}else{
							if(headUrl!=null){
								insertId = dataHelper.SaveUserInfo(user,ImageUtil.getBytesFromUrl(headUrl));
							}else{
								insertId = dataHelper.SaveUserInfo(user,null);
							}
						}
						if(insertId>0L){
							//Toast.makeText(AccountActivity.this, "已经授权成功,将跳转到选择默认的登录用户界面!", Toast.LENGTH_LONG).show();
						}
						Log.d(TAG+"插入数据库的id是", insertId.toString());
						
						userList = dataHelper.GetUserList(false);
						adapater = new UserAdapater();
						adapater.notifyDataSetChanged();//刷新listview
						listView.setAdapter(adapater);
						
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
					Log.e(TAG, userInfo);
				}
				Log.e(TAG, veryfier);
			}
		}
	};


	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position,
			long arg3) {
		CharSequence [] items = null;
		items= new CharSequence[]{"删除账号","取消"};
		new AlertDialog.Builder(AccountActivity.this).setTitle("选项").setItems(items,new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0: {
							String userId = userList.get(position).getUserId();
							dataHelper.DelUserInfo(userId);//删除数据库记录
							SharedPreferences preferences = getSharedPreferences("default_user", Activity.MODE_PRIVATE);
							SharedPreferences.Editor editor = preferences.edit();
							if(preferences.getString("user_default_name", "").equals(userId)){
								editor.putString("user_default_nick", "");
								editor.putString("user_default_name", "");
								editor.commit();//清除里面保存的记录SharedPreferences
							}
							userList = dataHelper.GetUserList(false);
							adapater = new UserAdapater();
							adapater.notifyDataSetChanged();//刷新listview
							listView.setAdapter(adapater);
						}
							break;
						case 1: {
						}
							break;
						default:
							break;
						}
			}
		}).show();
		return false;
	}
}

public class AuthorizeActivity extends Activity {
	private static final String TAG = "AuthorizeActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
		WebView webView = (WebView) findViewById(R.id.web);
		webView.setWebViewClient(new MyWebViewClient());
		Intent intent = this.getIntent();
		if (!intent.equals(null)) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				if (bundle.containsKey("url")) {
					String url = bundle.getString("url");
					WebSettings webSettings = webView.getSettings();
					webSettings.setJavaScriptEnabled(true);
					webSettings.setSupportZoom(true);
					webView.requestFocus();
					webView.loadUrl(url);
				}
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			WebView webView = (WebView) findViewById(R.id.web);
			if (webView.canGoBack()) {
				webView.goBack();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	public class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Pattern p = Pattern.compile("^" + MyWeiboSync.CALLBACK_URL
					+ ".*oauth_verifier=(\\d+)");
			Matcher m = p.matcher(url);
			if (m.find()) {
				Intent intent = new Intent();
				intent.setAction("com.weibo.caigang.getverifier");
				String veryfier = m.group(1);
				intent.putExtra("veryfier", veryfier);
				sendBroadcast(intent);
				finish();
			}
		}
	}
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#b8c0c8" android:layout_width="fill_parent" android:layout_height="fill_parent">
	<RelativeLayout android:id="@+id/account_top" android:background="@drawable/header" android:layout_width="fill_parent" android:layout_height="wrap_content">
	    <TextView android:textSize="22.0sp" android:text="账号管理" android:textColor="#ffffffff" android:ellipsize="middle" android:gravity="center_horizontal" android:id="@+id/account_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true"  android:layout_centerInParent="true" android:layout_alignWithParentIfMissing="true" />
	</RelativeLayout>
	
	<ListView android:id="@id/android:list"  android:background="@drawable/panel_bg" android:layout_marginTop="20.0dip" android:layout_marginLeft="10.0dip" android:layout_marginRight="10.0dip" android:padding="5.0dip" android:layout_below="@id/account_top" android:layout_width="fill_parent" android:cacheColorHint="#00000000"
		android:layout_height="wrap_content" android:layout_weight="1" android:divider="@drawable/list_divider"/>
		
	<RelativeLayout android:id="@+id/account_bottom" android:layout_width="fill_parent" android:layout_height="40.0dip" android:gravity="center" android:layout_alignParentBottom="true">
		<Button android:id="@+id/account_back_btn" android:layout_width="40.0dip" android:drawableTop="@drawable/btn_back_selector" android:background="@drawable/bottom_back_bg"
			android:layout_height="40.0dip"  android:layout_alignParentLeft="true"/>
		<Button android:id="@+id/account_tohome_btn" android:layout_width="40.0dip"
			android:layout_height="40.0dip" android:drawableTop="@drawable/btn_home_selector" android:background="@drawable/bottom_home_bg" android:layout_alignParentRight="true"/>
		<LinearLayout android:layout_marginLeft="35.0dip" android:layout_toRightOf="@id/account_back_btn" android:layout_toLeftOf="@id/account_tohome_btn" android:layout_centerInParent="true" android:orientation="horizontal" android:id="@+id/account_add_btn_bar" android:layout_width="fill_parent" android:layout_height="fill_parent">	
			<TextView android:textSize="16.0dip" android:text="添加账号" android:textColor="@color/bottom_button_text_selector" android:gravity="center" android:background="@drawable/account_add_btn_selector" android:focusable="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
		</LinearLayout>	
	</RelativeLayout>
	
	<RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:layout_above="@id/account_bottom" android:layout_marginBottom="40.0dip">
		<ImageView 	android:id="@+id/user_default_headicon" android:layout_width="120.0dip" android:layout_height="78.0dip"/>
	</RelativeLayout>
	
</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:paddingTop="3.0dip" android:orientation="horizontal" android:background="@drawable/listitem_selector"  android:layout_width="fill_parent" android:layout_height="wrap_content">
	<RelativeLayout android:layout_width="50.0dip" android:layout_height="50.0dip" android:layout_weight="0.0">
		<ImageView android:id="@+id/user_headicon" android:layout_width="45.0dip" android:layout_height="45.0dip" android:scaleType="fitCenter" android:layout_centerInParent="true" />
	</RelativeLayout>
	<RelativeLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="4.0dip" android:layout_weight="1.0">
		<TextView android:id="@+id/user_nick" android:textColor="#000000" android:layout_width="wrap_content" android:layout_height="32.0dip" android:textSize="14.0sp" android:layout_alignParentLeft="true"/>
		<TextView android:id="@+id/user_name" android:layout_marginLeft="6.0dip" android:layout_below="@id/user_nick" android:textColor="#ff000000" android:layout_width="wrap_content" android:layout_height="32.0dip" android:textSize="8.0sp" android:layout_alignParentLeft="true"/>
	</RelativeLayout>
</LinearLayout>


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<WebView   
		android:id="@+id/web"
		android:layout_height="wrap_content"            
		android:layout_width="wrap_content"  
		/>	
</LinearLayout>



  • Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 
  • 大小: 59.6 KB
  • Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 
  • 大小: 50.2 KB
  • Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 
  • 大小: 60.2 KB
  • Android腾讯微博客户端开发三:多账号管理的实现
            
    
    博客分类: 腾讯微博客户端 Android 微博 多账号 webview broadcast 
  • 大小: 98.7 KB