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

来源:互联网 发布:门头设计软件 编辑:程序博客网 时间:2024/04/29 20:17

刚开始下载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";@Overrideprotected 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 exceptione.printStackTrace();}}}private void firstused() {// TODO Auto-generated method stuboAuthDialog = new AlertDialog.Builder(this).setTitle("消息").setMessage("第一次使用请进行授权").setPositiveButton("授权", new buttonlistener()).show();}//授权按钮,开始授权class buttonlistener implements android.content.DialogInterface.OnClickListener {@Overridepublic void onClick(DialogInterface arg0, int arg1) {// TODO Auto-generated method stubtry {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{@Overridepublic void run() {// TODO Auto-generated method stubtry {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 exceptione.printStackTrace();}}}private class UserInfo implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubtry {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 exceptione.printStackTrace();}}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {//处理返回的数据// TODO Auto-generated method stubif(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 exceptione.printStackTrace();}}}}//等待后台服务下载网络数据Runnable runnable = new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {System.out.println("sleep 2 sec!!!!"); Thread.sleep(2000);//数据读取到后,跳转到下个界面,就是微博的显示主界面startActivity(new Intent(LoginActivity.this,MaintabActivity.class));finish();} catch (Exception e) {// TODO: handle exceptione.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() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubIntent 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() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubIntent 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 的一个ButtonloadingDialog.setIndeterminate(false);// 设置ProgressDialog 的进度条是否不明确loadingDialog.setCancelable(true);// 设置ProgressDialog 是否可以按退回按键取消loadingDialog.show();// 让ProgressDialog显示}//接受广播,后台下载完成,退出。private class MyReceive extends BroadcastReceiver {@Overridepublic void onReceive(Context arg0, Intent arg1) {String action = arg1.getAction();if (action.equals(LOGIN_FINISH)) {LoginActivity.this.finish();}}}@Overridepublic 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;}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();LoginActivity.this.unregisterReceiver(myReceive);}}

0 0
原创粉丝点击