安卓----------腾讯微博客户端开发1

刚开始下载http://www.eoeandroid.com/thread-164803-1-1.html这个的代码,但是启动后很多问题,于是自己试着照代码重新写一遍,解决问题的过程中也能学习学习.

首先做的程序登录界面,这个activity里面主要是进行oauth的认证,获取accesstoken信息存储到本地,每次启动时会去读取这个数据作出判别。

因为源代码使用的是oauth1认证,而腾讯现在已经停止了,所以改成了oauth2的认证,两种方法都差不多。

需要注意的几点:

1:网络等权限要打开,否则会报错。

2:android3.0版本开始就强制不能主线程中访问网络,要把访问网络放在独立的线程中。

以下是代码:

package com.example.weibo;


import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

import oauth.signpost.OAuth;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;

public class LoginActivity extends Activity {
	//登录界面,读取数据,没有数据需要进行授权
	private SharedPreferences sharedPreferences;
	private AlertDialog oAuthDialog;
	private OAuthV2 oAuthV2;
	boolean netSataus = false;
	private UserAPI userAPI;
	private String response;
	private ProgressDialog loadingDialog;
	private MyReceive myReceive;
	private IntentFilter intentFilter;
	
	//private MyHandler myHandler;
	
	public static final String LOGIN_FINISH = "com.broadcast.loadfinish";
	
	public static final String INTERNET = "com.broadcast.ISINTERNET";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		myReceive = new MyReceive();
		intentFilter = new IntentFilter();
		intentFilter.addAction(LOGIN_FINISH);
		LoginActivity.this.registerReceiver(myReceive, intentFilter);
		//myHandler = new MyHandler();
		//首先检查网络
		NetworkStatus();
		if(netSataus)
		{
			try {
				sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
				//判断是够有用户存在,是否已经有了OAUTH_TOKEN,OAUTH_TOKEN_SECRET,存在说明不是第一次登陆
				boolean firstuse = sharedPreferences.getBoolean("isfirstuse", true);
				String OAUTH_TOKEN = sharedPreferences.getString(OAuth.OAUTH_TOKEN, null);
				String OAUTH_TOKEN_SECRET = sharedPreferences.getString(OAuth.OAUTH_TOKEN_SECRET, null);
				
				//测试是否存到数据
				//String useinfo = sharedPreferences.getString("userinfo", null);
				//System.out.println("get userinfo------>"+useinfo);
				if(firstuse != false && OAUTH_TOKEN != null && OAUTH_TOKEN_SECRET != null)
				{
					System.out.println("可以直接登录");
					new Thread(runnable).start();
				}
				else
				{
					System.out.println("第一次登录");
					firstused();
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}

	private void firstused() {
		// TODO Auto-generated method stub
		oAuthDialog = new AlertDialog.Builder(this).setTitle("消息").
				setMessage("第一次使用请进行授权").
				setPositiveButton("授权", new buttonlistener()).show();
	}
	
	//授权按钮,开始授权
		class buttonlistener implements android.content.DialogInterface.OnClickListener {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				try {
				System.out.println("开始授权");			
				oAuthV2=new OAuthV2(Constants.AUTH_CALLBACK_URL);
				oAuthV2.setClientId(Constants.CONSUMER_KEY);
				oAuthV2.setClientSecret(Constants.CONSUMER_SECRET);
				OAuthV2Client.getQHttpClient().shutdownConnection();
				Thread thread=new OAuthThread();
				thread.start();			
				oAuthDialog.cancel();
				loading();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	
	private class OAuthThread extends Thread{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				System.out.println("跳转到授权界面");
				OAuthV2Client.accessToken(oAuthV2);
				//跳转到腾讯的微博授权界面登录
				Intent intent = new Intent(LoginActivity.this, OAuthV2AuthorizeWebView.class);
				intent.putExtra("oauth", oAuthV2);
			    startActivityForResult(intent,2);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		
	}
	
	private class UserInfo implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				OAuthV2Client.accessToken(oAuthV2);
				userAPI=new UserAPI(OAuthConstants.OAUTH_VERSION_2_A);    
				response=userAPI.info(oAuthV2, "json");
				System.out.println("response------>" + response); 
				userAPI.shutdownConnection();
				Editor edit = sharedPreferences.edit();
				edit.putString("userinfo", response);
				edit.commit(); 
				new loginTask(LoginActivity.this).execute();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//处理返回的数据
		// TODO Auto-generated method stub
		if(requestCode == 2)
		{
			if(resultCode == OAuthV2AuthorizeWebView.RESULT_CODE)
			{
				oAuthV2 = (OAuthV2)data.getExtras().getSerializable("oauth");
				 System.out.println("oAuthV2------>" + oAuthV2);
				try {
					if(OAuthV2Client.accessToken(oAuthV2))
						System.out.println("授权完成!");
						//这里必须建个线程去读取数据,因为android在后面的版本里,主线程是不能做网络操作的
						//之前这里没有建线程,导致用userAPI去读取用户数据时一直是空
						//创建一个runnable对象,启动
						UserInfo thread1 =new UserInfo();
						new Thread(thread1).start();
		                
						System.out.println("AccessToken------>" + oAuthV2.getAccessToken());
						//这个是AccessToken的有效时间
						System.out.println("ExpiresIn------>" + oAuthV2.getExpiresIn());
						System.out.println("getClientSecret------>" + oAuthV2.getClientSecret());
						//把数据存储到本地
						Editor edit = sharedPreferences.edit();
						edit.putString(OAuth.OAUTH_TOKEN, oAuthV2.getAccessToken());
						edit.putString(OAuth.OAUTH_TOKEN_SECRET, oAuthV2.getClientSecret());
						edit.putBoolean("isfirstused", false);
						edit.commit(); 
						new loginTask(LoginActivity.this).execute();
						new Thread(runnable).start();
						loadingDialog.cancel(); 
					
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
			}
		}
	}

	//等待后台服务下载网络数据
	Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				System.out.println("sleep 2 sec!!!!"); 
				Thread.sleep(2000);
				//数据读取到后,跳转到下个界面,就是微博的显示主界面
				startActivity(new Intent(LoginActivity.this,MaintabActivity.class));
				finish();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	};
	private boolean NetworkStatus() {
		// TODO Auto-generated method stub
		// 使用ConnectivityManager来判断网络链接状态
		ConnectivityManager conManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		//获取网络信息
		NetworkInfo networkInfo =  conManager.getActiveNetworkInfo();
		if(networkInfo != null)
		{
			netSataus = networkInfo.isAvailable();
		}
		//没有网络时
		if(!netSataus)
		{
			//创建一个Alertdialog,对话框
			Builder b = new AlertDialog.Builder(this).setTitle("没有可用网络")
					.setMessage("是否进行设置");
			b.setPositiveButton("是", new DialogInterface.OnClickListener() {		

		
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Intent mIntent = new Intent();
					//开启网络
					ComponentName componentName = new ComponentName(
							"com.android.settings", 
							"com.android.settings.WirelessSettings");
					mIntent.setComponent(componentName);
					mIntent.setAction("android.intent.action.VIEW");
					startActivityForResult(mIntent, 0);
				}
			}).setNeutralButton("否", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Intent intent = new Intent();
					intent.setClass(LoginActivity.this, MaintabActivity.class);
					
					Intent intent2 = new Intent();
					intent2.setAction(INTERNET);
					LoginActivity.this.sendBroadcast(intent2);
					LoginActivity.this.finish();
				}
			}).show();
		}
		return netSataus;
	}

	private void loading() {
		loadingDialog = new ProgressDialog(this);
		// 实例化
		loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		// 设置进度条风格,风格为圆形,旋转的
		loadingDialog.setTitle("正在连接,请稍后");
		// 设置ProgressDialog 标题
		// mypDialog.setMessage(getResources().getString(R.string.second));
		// //设置ProgressDialog 提示信息
		// mypDialog.setIcon(R.drawable.android);
		// //设置ProgressDialog 标题图标
		//loadingDialog.setButton("取消", new exitButtonlistener());
		// //设置ProgressDialog 的一个Button
		loadingDialog.setIndeterminate(false);
		// 设置ProgressDialog 的进度条是否不明确
		loadingDialog.setCancelable(true);
		// 设置ProgressDialog 是否可以按退回按键取消
		loadingDialog.show();
		// 让ProgressDialog显示
	}
	
	//接受广播,后台下载完成,退出。
		private class MyReceive extends BroadcastReceiver {

			@Override
			public void onReceive(Context arg0, Intent arg1) {			
				String action = arg1.getAction();
				if (action.equals(LOGIN_FINISH)) {
					LoginActivity.this.finish();
				}
			}
		}
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		LoginActivity.this.unregisterReceiver(myReceive);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值