ANDROID_MARS学习笔记_S04_006_用获取access_token,access_token_secrect

一、代码流程

1.MainActivity会开启PrepareRequestTokenActivity

2.PrepareRequestTokenActivity会根据配置文件的CONSUMER_KEY、CONSUMER_SECRET生成consumer

根据REQUEST_URL、ACCESS_URL、AUTHORIZE_URL生成provider,然后开启OAuthRequestTokenTask,执行异步操作,访问腾讯网络

3.在OAuthRequestTokenTask的doInBackground()中,provider.retrieveRequestToken()会指定回调地址,这里是指定“x-oauthflow://callback”

而在manifext.xml中,为PrepareRequestTokenActivity设置了<data android:scheme="x-oauthflow" android:host="callback"/>,所以一当OAuthRequestTokenTask成功返回后回调PrepareRequestTokenActivity,而PrepareRequestTokenActivity又设置了android:launchMode="singleTask",所以回调是是调用PrepareRequestTokenActivity的onNewIntent(),而不是onCreate()。

二、代码
1.xml
(1)activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent"
 6     >
 7         <Button android:id="@+id/btn_launch_oauth"
 8                 android:layout_width="wrap_content"
 9                 android:layout_height="wrap_content"
10                 android:text="Launch OAuth Flow"
11                 android:onClick="startPrepareRequestTokenActivity"/>
12
13             <TextView android:id="@+id/response_code"
14                 android:layout_width="wrap_content"
15                 android:layout_height="wrap_content"
16                 android:text=""
17                 android:textColor="#FFFFFF"
18                 android:typeface="normal"/>
19 </LinearLayout>

(2)AndroidManifest.xml

 1         <activity android:name=".PrepareRequestTokenActivity" android:launchMode="singleTask">
 2             <intent-filter>
 3                 <action android:name="android.intent.action.VIEW"/>
 4                 <category android:name="android.intent.category.DEFAULT"/>
 5                 <category android:name="android.intent.category.BROWSABLE"/>
 6                 <data android:scheme="x-oauthflow" android:host="callback"/>
 7             </intent-filter>
 8         </activity>
 9     </application>
10     <uses-permission android:name="android.permission.INTERNET"/>
11     <uses-permission android:name="android.permission.READ_CONTACTS" />

2.java
(1)MainActivity.java

 1 package org.oauth;
 2
 3 import org.oauth.R;
 4
 5 import android.app.Activity;
 6 import android.content.Intent;
 7 import android.os.Bundle;
 8 import android.view.View;
 9
10 public class MainActivity extends Activity {
11
12     @Override
13     protected void onCreate(Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
15         setContentView(R.layout.activity_main);
16     }
17
18     public void startPrepareRequestTokenActivity(View view) {
19         startActivity(new Intent().setClass(view.getContext(), PrepareRequestTokenActivity.class));
20     }
21 }

(2)PrepareRequestTokenActivity.java

 1 package org.oauth;
 2
 3 import oauth.signpost.OAuthConsumer;
 4 import oauth.signpost.OAuthProvider;
 5 import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
 6 import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
 7 import android.app.Activity;
 8 import android.content.Intent;
 9 import android.content.SharedPreferences;
10 import android.net.Uri;
11 import android.os.Bundle;
12 import android.preference.PreferenceManager;
13
14 public class PrepareRequestTokenActivity extends Activity {
15
16     private OAuthConsumer consumer;
17     private OAuthProvider provider;
18
19     @Override
20     protected void onCreate(Bundle savedInstanceState) {
21         super.onCreate(savedInstanceState);
22
23         consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
24         provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL, Constants.ACCESS_URL, Constants.AUTHORIZE_URL);
25         new OAuthRequestTokenTask(this, consumer, provider).execute();
26     }
27
28     //由于设置了<activity android:name=".PrepareRequestTokenActivity" android:launchMode="singleTask">
29     //所以回调会调用此方法,而不要调用 onCreate()
30     @Override
31     public void onNewIntent(Intent intent) {
32         super.onNewIntent(intent);
33         //最后获取的access_token,access_token_secet都存在prefs
34         SharedPreferences prefs = PreferenceManager
35                 .getDefaultSharedPreferences(this);
36         final Uri uri = intent.getData();
37         System.out.println(uri.toString());
38         if (uri != null
39                 && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
40             new RetrieveAccessTokenTask(this, consumer, provider, prefs)
41                     .execute(uri);
42             finish();
43         }
44     }
45 }

(3)OAuthRequestTokenTask.java

 1 package org.oauth;
 2
 3
 4 import oauth.signpost.OAuthConsumer;
 5 import oauth.signpost.OAuthProvider;
 6 import oauth.signpost.exception.OAuthCommunicationException;
 7 import oauth.signpost.exception.OAuthExpectationFailedException;
 8 import oauth.signpost.exception.OAuthMessageSignerException;
 9 import oauth.signpost.exception.OAuthNotAuthorizedException;
10 import android.content.Context;
11 import android.content.Intent;
12 import android.net.Uri;
13 import android.os.AsyncTask;
14
15 public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
16
17     private Context context;
18     private OAuthConsumer consumer;
19     private OAuthProvider provider;
20
21     public OAuthRequestTokenTask(Context context, OAuthConsumer consumer,
22             OAuthProvider provider) {
23         super();
24         this.context = context;
25         this.consumer = consumer;
26         this.provider = provider;
27     }
28
29     @Override
30     protected Void doInBackground(Void... params) {
31         try {
32             System.out.println("请求Request Token之前" + consumer.getToken());
33             //retrieveRequestToken的第二个参数是回调URL
34             final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
35             System.out.println("请求Request Token之后" + consumer.getToken());
36             System.out.println("url---->" + url);
37             Uri uri = Uri.parse(url);
38             //隐式的启动Activity
39             //tel://21983129863
40             //sms://767868698769
41             //https://.......会启动浏览器
42             Intent intent = new Intent(Intent.ACTION_VIEW, uri).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
43                     | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
44             context.startActivity(intent);
45         } catch (Exception e) {
46             // TODO Auto-generated catch block
47             e.printStackTrace();
48         }
49         return null;
50     }
51
52 }

(4)RetrieveAccessTokenTask.java

 1 package org.oauth;
 2
 3 import oauth.signpost.OAuth;
 4 import oauth.signpost.OAuthConsumer;
 5 import oauth.signpost.OAuthProvider;
 6 import android.content.Context;
 7 import android.content.Intent;
 8 import android.content.SharedPreferences;
 9 import android.content.SharedPreferences.Editor;
10 import android.net.Uri;
11 import android.os.AsyncTask;
12 import android.util.Log;
13
14 public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
15
16     final String TAG = "OAuth";
17
18     private Context    context;
19     private OAuthProvider provider;
20     private OAuthConsumer consumer;
21     private SharedPreferences prefs;
22
23     public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
24         this.context = context;
25         this.consumer = consumer;
26         this.provider = provider;
27         this.prefs=prefs;
28     }
29
30
31     @Override
32     protected Void doInBackground(Uri...params) {
33         final Uri uri = params[0];
34
35         final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
36
37         try {
38             provider.retrieveAccessToken(consumer, oauth_verifier);//会访问ACCESS_URL
39
40             final Editor edit = prefs.edit();
41             edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
42             edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
43             edit.commit();
44
45             String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
46             String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
47
48             consumer.setTokenWithSecret(token, secret);
49             context.startActivity(new Intent(context,MainActivity.class));
50
51             Log.i(TAG, "OAuth - Access Token Retrieved");
52
53         } catch (Exception e) {
54             Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
55         }
56
57         return null;
58     }
59 }

(5)Constants.java

 1 package org.oauth;
 2
 3 public class Constants {
 4
 5     //腾讯所分配的APP_KEY
 6     public static final String CONSUMER_KEY = "99e9494ff07e42489f4ace16b63e1f47";
 7     //腾讯所分配的APP_SECRET
 8     public static final String CONSUMER_SECRET = "154f6f9ab4c1cf527f8ad8ab1f8e1ec9";
 9     //用于获取未授权的request token
10     public static final String REQUEST_URL = "https://open.t.qq.com/cgi-bin/request_token";
11     //用于获取access token
12     public static final String ACCESS_URL = "https://open.t.qq.com/cgi-bin/access_token";
13     //用于对未授权的request token进行授权
14     public static final String AUTHORIZE_URL = "https://open.t.qq.com/cgi-bin/authorize";
15
16     public static final String ENCODING = "UTF-8";
17
18     //Manifest设置PrepareRequestTokenActivity时也有设置此项
19     public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow";
20     public static final String OAUTH_CALLBACK_HOST = "callback";
21     //回调地址
22     public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
23
24 }
时间: 2024-09-29 02:00:42

ANDROID_MARS学习笔记_S04_006_用获取access_token,access_token_secrect的相关文章

sencha touch权威指南---学习笔记5-经纬度获取计算直线距离

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta charset="utf-8" />    <title></title>    <link rel="stylesheet" href="sdk-touch/resources/css/sencha-touch.

linux学习笔记一:获取命令帮助

linux命令超多,忘记命令的使用方式.格式是很平常的事 囧.能够使用系统自带的帮助文件获取到相关的信息是学习linux的必备基本功! 下面记录几个常用的帮助命令,只为加深本菜的记忆,有不对的地方请看到这篇博文的大大加以指导,感激不尽! 简要介绍下命令,命令分为两大种类. 一种为shell自带的一些基础命令,称为内部命令.该类命令集成在shell内部,执行速度比外部命令快. 还有一种称为外部命令,该类命令是额外安装的,开机不自动加载,在需要使用时通过路径查找(printenv中的PATH项),加

ANDROID_MARS学习笔记_S05_001_用SensorManager获取传感器

1. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //得到SensorManager对象 sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); sensorButton = (Button)findV

ANDROID_MARS学习笔记_S04_007_从服务器获取微博数据时间线

一.代码 1.xml(1)activity_main.xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width=&qu

ANDROID_MARS学习笔记_S03_001_获取蓝牙匹配列表

一.代码 1.xml(1)AndroidManifest.xml 增加 1 <uses-permission android:name="android.permission.BLUETOOTH"/> 2.java(1)MainActivity.java 1 package com.bluetooth1; 2 3 import java.util.Iterator; 4 import java.util.Set; 5 6 import android.app.Activit

ANDROID_MARS学习笔记_S01原始版_013_广播机制二

一.代码1.xml(1)main.xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width="fill_pa

ANDROID_MARS学习笔记_S01_002View、监听器初步

一.View.监听器介绍 二.在Activity中获取view和设置属性,设置button的监听器 1.activity_main.xml 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_par

php学习笔记3--php中获取时间与实际时间不符

问题描述:在php脚本中使用date()获取服务器时间时总是与实际时间相差几个小时. 可能原因:php配置文件中时区的设置出现问题 解决方法: 方法1. php.ini文件中date.timezone=PRC 或者date.timezone = Asia/Shanghai 方法2. 在调用date()等时间相关的函数之前调用:date_default_timezone_set('PRC'); 或者date_default_timezone_set('Asia/Shanghai');

ANDROID_MARS学习笔记_S01原始版_022_MP3PLAYER002_本地及remote标签

一.简介 1.在main.xml中用TabHost.TabWidget.FrameLayout标签作布局 2.在MainActivity中生成TabHost.TabSpec,调用setIndicator().setContent().addTab(),用Intent指明要跳转的tab对应的class 3.在onResume中写获取本地mp3信息的代码,代码在onResume中,则切换tab时,mp3信息每次都会更新 二.代码1.xml(1)main.xml 1 <TabHost xmlns:an