因爲公司項目的須要,要實如今項目中使用第三方受權登陸以及分享文字和圖片等這樣的效果,幾經波折,查閱了一番資料,作了一個Demo。實現起來的效果仍是不錯的,不敢獨享,決定寫一個總結的教程,供你們互相交流、學習和參考,博主只求能和你們共同進步。但願能多多支持!java
這篇文章中,咱們使用到了Share SDK,它是爲iOS、Android、WP8的APP提供社會化功能的一個組件,目前支持如QQ、微信、新浪微博、騰訊微博、開心網、人人網、豆瓣、網易微博、搜狐微博、facebook、twitter、google+等國內外主流社交平臺。android
1、實現的效果圖json
主界面效果圖 api
受權登陸頁面效果圖安全
點擊分享按鈕彈出分享分享界面 微信
2、項目結構目錄網絡
3、編碼前的準備工做app
一、獲取Libs ide
Libs包含ShareSDK的類庫,具體包括三個文件夾,分別是ShareSDK的全局依賴庫、ShareSDK當前支持的全部平臺工具庫和ShareSDK可視化UI的一些支持庫。「全局依賴庫」是集成ShareSDK的基礎,ShareSDK的任何平臺都依賴於這個庫,而「ShareSDK-GUI」提供的是一個測欄控件和一個快捷分享工具,以方便讀者更快速地集成ShareSDK。Libs下載地址
二、導入Libs
<1> 將「Libs\Global-Dependences」下的jar包複製到您的libs目錄下。
<2> 從「Libs\Platforms」中選擇您感興趣的平臺,比方說「新浪微博」、「QQ空間」、「騰訊微博」等,複製相應的壓縮包到你項目的libs目錄下並解壓
<3> 若是你決定使用shareSDK提供的快捷分享工具,還須要複製「Libs\ShareSDK-GUI」中複製「cn.sharesdk.onekeyshare.jar」到你的項目中。
<4> 通常來講,ADT會自動將你添加到libs目錄下的jar包添加到「Android Dependencies」中。可是若是你的開發環境不能自動加載ShareSDK的jar包到你的項目中,那麼只能手動添加,以下圖所示:
4、詳細的編碼實現
一、ShareSdK使用統一的格式管理你在不一樣平臺上註冊的開發者信息。這些信息都存放在項目的「assets/ShareSDKDevInfor.xml」中,ShareSDKDevInfor.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <DevInfor>
- <!--說明:
- 一、表格中的第一項
- <ShareSDK AppKey="api20" />
- 是必須的,其中的AppKey是你在Share SDK上註冊的開發者賬號的AppKey
-
- 二、全部集成到你項目的平臺都應該爲其在表格中填寫相對應的開發者信息,以新浪微博爲例:
- <SinaWeibo
- SortId="此平臺在分享列表中的位置,由開發者自行定義,能夠是任何整型數字,數值越大越靠後"
- AppKey="填寫你在新浪微博上註冊的AppKey"
- AppSecret="填寫你在新浪微博上註冊到的AppKey"
- Id="自定義字段,整形,用於你項目中對此平臺的識別符"
- RedirectUrl="填寫你在新浪微博上註冊的RedirectUrl" />
-
- 各個平臺註冊應用信息的地址以下:
- 新浪微博:http://open.weibo.com
- 騰訊微博:http://dev.t.qq.com
- QQ空間:http://connect.qq.com/intro/login/
- 網易微博:http://open.t.163.com
- 搜狐微博:http://open.t.sohu.com
- 豆瓣:http://developers.douban.com
- 人人網:http://dev.renren.com
- 開心網:http://open.kaixin001.com
- Instapaper:http://www.instapaper.com/main/request_oauth_consumer_token
- 有道雲筆記:http://note.youdao.com/open/developguide.html#app
- facebook:https://developers.facebook.com
- twitter:https://dev.twitter.com
- 搜狐隨身看:https://open.sohu.com
- QQ好友分享:http://mobile.qq.com/api/
- 微信:http://open.weixin.qq.com-->
-
- <ShareSDK
- AppKey = "api20"/>
-
- <SinaWeibo
- SortId="1"
- AppKey="3201194191"
- AppSecret="0334252914651e8f76bad63337b3b78f"
- Id="1"
- RedirectUrl="http://appgo.cn" />
-
- <TencentWeibo
- SortId="2"
- AppKey="801307650"
- AppSecret="ae36f4ee3946e1cbb98d6965b0b2ff5c"
- RedirectUri="http://sharesdk.cn"
- Id="2" />
-
- <QZone
- SortId="3"
- AppId="100371282"
- AppKey="aed9b0303e3ed1e27bae87c33761161d"
- Id="3"
- RedirectUrl="http://www.shareSDK.cn" />
-
- <Renren
- SortId="4"
- AppId="226427"
- ApiKey="fc5b8aed373c4c27a05b712acba0f8c3"
- Id="4"
- SecretKey="f29df781abdd4f49beca5a2194676ca4" />
-
- </DevInfor>
二、配置AndroidManifest.xml,不一樣的集成度須要在AndroidManifest.xml中添加的內容也不同。可是首先你須要添加下面的權限列表:
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- <uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />
- <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.READ_PHONE_STATE" />
這些權限將容許你的項目和ShareSDK獲取鏈接網絡的權限、獲取你的設備網絡狀態的權限、實現https安全鏈接的權限、讀取手機設備狀態的權限和保存必要配置的權限。通常來講,即使不集成ShareSDK,大部分的項目也都會註冊申請這些權限。
注意:你們在加入這個"android.permission.WRITE_APN_SETTINGS"權限的時候,可能有些讀者的編譯器會報錯,博主就遇到了這樣的狀況,這個是ADT Lint工具的問題。
解決的辦法是:依照下面的路徑「Window —> Preferences —> android—> lint error checking」打開lint的配置頁面,而後去掉頁面頂部的兩個勾選,以後再clean項目就能處理。以下圖所示:
三、其次,爲了受權操做能夠順利完成,須要在application下注冊下面的Activity:
- <activity
- android:name="cn.sharesdk.framework.AuthorizeActivity"
- android:configChanges="keyboardHidden|orientation"
- android:screenOrientation="portrait"
- android:theme="@android:style/Theme.Translucent.NoTitleBar"
- android:windowSoftInputMode="stateHidden|adjustResize" >
- </activity>
AuthorizeActivity的路徑是固定的,必定要在「cn.sharesdk.framework」下,由於他在Share-Core包中。
四、添加布局頁面,首先是主界面的佈局頁面,activity_main.xml:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <Button
- android:id="@+id/btnLogin"
- android:layout_width="fill_parent"
- android:layout_height="44dp"
- android:layout_above="@+id/btnShareAllGui"
- android:layout_centerHorizontal="true"
- android:layout_margin="5dp"
- android:background="@drawable/btn_back"
- android:text="用戶受權登陸"
- android:textSize="16dp"/>
-
- <Button
- android:id="@+id/btnShareAllGui"
- android:layout_width="fill_parent"
- android:layout_height="44dp"
- android:layout_above="@+id/btnShareAll"
- android:layout_margin="5dp"
- android:background="@drawable/btn_back"
- android:text="分享所有(有分享界面)"
- android:textSize="16dp" />
-
- <Button
- android:id="@+id/btnShareAll"
- android:layout_width="fill_parent"
- android:layout_height="44dp"
- android:layout_alignParentRight="true"
- android:layout_centerVertical="true"
- android:layout_margin="5dp"
- android:background="@drawable/btn_back"
- android:text="分享所有(無界面,直接分享)"
- android:textSize="16dp" />
-
- <Button
- android:id="@+id/btnUserInfo"
- android:layout_width="fill_parent"
- android:layout_height="44dp"
- android:layout_below="@+id/btnShareAll"
- android:layout_margin="5dp"
- android:layout_marginTop="41dp"
- android:background="@drawable/btn_back"
- android:text="獲取受權用戶資料"
- android:textSize="16dp" />
-
- </RelativeLayout>
五、用戶受權登陸的佈局頁面,activity_auth.xml:
六、得到用戶信息佈局界面,activity_userinfo.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#fff5f5f5"
- android:orientation="vertical" >
-
-
- <cn.sharesdk.framework.TitleLayout
- android:id="@+id/llTitle"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="@drawable/title_back" />
-
- <Button
- android:id="@+id/btnQz"
- android:layout_width="fill_parent"
- android:layout_height="44dp"
- android:layout_centerVertical="true"
- android:layout_margin="5dp"
- android:background="@drawable/btn_back"
- android:text="@string/get_user_info_qz"
- android:textSize="16dp" />
-
- <Button
- android:id="@+id/btnRr"
- android:layout_width="fill_parent"
- android:layout_height="44dp"
- android:layout_above="@+id/btnQz"
- android:layout_margin="5dp"
- android:background="@drawable/btn_back"
- android:text="@string/get_user_info_rr"
- android:textSize="16dp" />
-
- <Button
- android:id="@+id/btnSw"
- android:layout_width="fill_parent"
- android:layout_height="44dp"
- android:layout_above="@+id/btnRr"
- android:layout_margin="5dp"
- android:background="@drawable/btn_back"
- android:text="@string/get_user_info_sw"
- android:textSize="16dp" />
-
- <Button
- android:id="@+id/btnTc"
- android:layout_width="fill_parent"
- android:layout_height="44dp"
- android:layout_below="@+id/btnQz"
- android:layout_centerHorizontal="true"
- android:layout_margin="5dp"
- android:background="@drawable/btn_back"
- android:text="@string/get_user_info_tc"
- android:textSize="16dp" />
-
- </RelativeLayout>
七、顯示用戶得到的信息佈局界面,activity_userinfo.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#fff5f5f5"
- android:orientation="vertical" >
-
-
- <cn.sharesdk.framework.TitleLayout
- android:id="@+id/llTitle"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="@drawable/title_back" />
-
- <ScrollView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_below="@id/llTitle"
- android:paddingBottom="10dp"
- android:paddingLeft="10dp"
- android:paddingTop="10dp" >
-
- <TextView
- android:id="@+id/tvJson"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginRight="10dp"
- android:autoLink="all"
- android:background="@drawable/list_item_single_normal"
- android:textColor="#ff000000" />
- </ScrollView>
-
- </RelativeLayout>
八、主界面入口Activity類,MainActivity.java:
- package com.yangyu.activity;
-
- import java.io.File;
- import java.io.FileOutputStream;
-
- import android.app.Activity;
- import android.content.Intent;
- import android.graphics.Bitmap;
- import android.graphics.Bitmap.CompressFormat;
- import android.graphics.BitmapFactory;
- import android.os.Bundle;
- import android.os.Environment;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import cn.sharesdk.framework.AbstractWeibo;
- import cn.sharesdk.onekeyshare.ShareAllGird;
-
- import com.yangyu.mysharethings.R;
-
- public class MainActivity extends Activity implements OnClickListener {
-
- public static String TEST_IMAGE;
-
-
- private Button authLoginBtn,shareGuiBtn,shareBtn,getInfoBtn;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
-
- AbstractWeibo.initSDK(this);
-
- initImagePath();
-
- initView();
-
- initData();
- }
-
-
- private void initView(){
- authLoginBtn = (Button)findViewById(R.id.btnLogin);
- shareGuiBtn = (Button)findViewById(R.id.btnShareAllGui);
- shareBtn = (Button)findViewById(R.id.btnShareAll);
- getInfoBtn = (Button)findViewById(R.id.btnUserInfo);
- }
-
-
- private void initData(){
-
- authLoginBtn.setOnClickListener(this);
- shareGuiBtn.setOnClickListener(this);
- shareBtn.setOnClickListener(this);
- getInfoBtn.setOnClickListener(this);
- }
-
-
- private void initImagePath() {
- try {
- if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
- && Environment.getExternalStorageDirectory().exists()) {
- TEST_IMAGE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/pic.png";
- }
- else {
- TEST_IMAGE = getApplication().getFilesDir().getAbsolutePath() + "/pic.png";
- }
- File file = new File(TEST_IMAGE);
-
- if (!file.exists()) {
- file.createNewFile();
- Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
- FileOutputStream fos = new FileOutputStream(file);
- pic.compress(CompressFormat.JPEG, 100, fos);
- fos.flush();
- fos.close();
- }
- } catch(Throwable t) {
- t.printStackTrace();
- TEST_IMAGE = null;
- }
- }
-
-
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.btnLogin:
- startActivity(new Intent(MainActivity.this,AuthActivity.class));
- break;
- case R.id.btnShareAllGui:
- showGrid(false);
- break;
- case R.id.btnShareAll:
- showGrid(true);
- break;
- case R.id.btnUserInfo:
-
- Intent i = new Intent(this, GetInforActivity.class);
- startActivity(i);
- break;
- default:
- break;
- }
-
- }
-
-
- private void showGrid(boolean silent) {
- Intent i = new Intent(this, ShareAllGird.class);
-
- i.putExtra("notif_icon", R.drawable.ic_launcher);
-
- i.putExtra("notif_title", this.getString(R.string.app_name));
-
-
- i.putExtra("title", this.getString(R.string.share));
-
- i.putExtra("titleUrl", "http://sharesdk.cn");
-
- i.putExtra("text", this.getString(R.string.share_content));
-
- i.putExtra("imagePath", MainActivity.TEST_IMAGE);
-
- i.putExtra("url", "http://sharesdk.cn");
-
- i.putExtra("thumbPath", MainActivity.TEST_IMAGE);
-
- i.putExtra("appPath", MainActivity.TEST_IMAGE);
-
- i.putExtra("comment", this.getString(R.string.share));
-
- i.putExtra("site", this.getString(R.string.app_name));
-
- i.putExtra("siteUrl", "http://sharesdk.cn");
-
-
- i.putExtra("silent", silent);
- this.startActivity(i);
- }
-
-
- public static String actionToString(int action) {
- switch (action) {
- case AbstractWeibo.ACTION_AUTHORIZING: return "ACTION_AUTHORIZING";
- case AbstractWeibo.ACTION_GETTING_FRIEND_LIST: return "ACTION_GETTING_FRIEND_LIST";
- case AbstractWeibo.ACTION_FOLLOWING_USER: return "ACTION_FOLLOWING_USER";
- case AbstractWeibo.ACTION_SENDING_DIRECT_MESSAGE: return "ACTION_SENDING_DIRECT_MESSAGE";
- case AbstractWeibo.ACTION_TIMELINE: return "ACTION_TIMELINE";
- case AbstractWeibo.ACTION_USER_INFOR: return "ACTION_USER_INFOR";
- case AbstractWeibo.ACTION_SHARE: return "ACTION_SHARE";
- default: {
- return "UNKNOWN";
- }
- }
- }
-
- protected void onDestroy() {
-
- AbstractWeibo.stopSDK(this);
- super.onDestroy();
- }
- }
集成ShareSDK須要至少在兩個地方添加代碼,包括:
<1> 在onCreate中插入下面的代碼:
- AbstractWeibo.initSDK(this);
這行代碼會初始化ShareSDK,此後對ShareSDK的操做都依次爲基礎。若是不在全部ShareSDK的操做以前調用這行代碼,會拋出空指針異常。
<2> 在項目的出口Activity的onDestroy方法的第一行插入下面的代碼:
- protected void onDestroy() {
-
- AbstractWeibo.stopSDK(this);
- super.onDestroy();
- }
這行代碼會結束ShareSDK的統計功能並釋放資源。若是這行代碼沒有被調用,那麼
「應用啓動次數」的統計將不會準確,由於應用可能歷來沒有被關閉。
InitSDK是能夠重複調用的,其實ShareSDK建議在你不肯定的時候調用這個方法,
來保證ShareSDK被正確初始化。而stopSDK一旦調用了,就必須從新調用InitSDK才能使
用ShareSDK的功能,不然會出現空指針異常。
在這段代碼中,還使用到了快捷分享,以下圖所示,點擊按鈕彈出快捷分享界面:
什麼是快捷分享呢?快捷分享是ShareSDK提供的一套基於其接口的GUI。經過簡單的配置,能夠在不考慮平臺的狀況下,調用不多的代碼,就完成分享的操做。快捷分享的jar包放在SDK解壓目錄的"Libs\ShareSDK-GUI"中,叫作"cn.sharesdk.oneshare.jar"。快捷分享使用了兩個Activity,須要在AndroidManifest.xml中註冊這兩個Activity:
- <activity
- android:name="cn.sharesdk.onekeyshare.ShareAllGird"
- android:configChanges="keyboardHidden|orientation"
- android:screenOrientation="portrait"
- android:theme="@android:style/Theme.Translucent.NoTitleBar"
- android:windowSoftInputMode="adjustPan|stateHidden" />
- <activity
- android:name="cn.sharesdk.onekeyshare.SharePage"
- android:configChanges="keyboardHidden|orientation"
- android:screenOrientation="portrait"
- android:windowSoftInputMode="stateHidden|adjustResize" />
九、賬號受權登陸界面,AuthActivity.java:
- package com.yangyu.activity;
-
- import java.util.HashMap;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Handler.Callback;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.CheckedTextView;
- import android.widget.Toast;
- import cn.sharesdk.framework.AbstractWeibo;
- import cn.sharesdk.framework.TitleLayout;
- import cn.sharesdk.framework.WeiboActionListener;
- import cn.sharesdk.renren.Renren;
- import cn.sharesdk.sina.weibo.SinaWeibo;
- import cn.sharesdk.tencent.qzone.QZone;
- import cn.sharesdk.tencent.weibo.TencentWeibo;
-
- import com.yangyu.mysharethings.R;
-
- public class AuthActivity extends Activity implements Callback, OnClickListener, WeiboActionListener {
-
- private CheckedTextView sinaCt,qzoneCt,tengxunCt,renrenCt;
-
-
- private Handler handler;
-
-
- private TitleLayout llTitle;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_auth);
-
- initView();
-
- initData();
- }
-
-
- private void initView(){
-
- handler = new Handler(this);
-
-
- llTitle = (TitleLayout) findViewById(R.id.llTitle);
-
-
- sinaCt = (CheckedTextView)findViewById(R.id.ctvSw);
- qzoneCt = (CheckedTextView)findViewById(R.id.ctvQz);
- tengxunCt = (CheckedTextView)findViewById(R.id.ctvTc);
- renrenCt = (CheckedTextView)findViewById(R.id.ctvRr);
- }
-
-
- private void initData(){
- llTitle.getBtnBack().setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- finish();
- }
- });
- llTitle.getTvTitle().setText("用戶受權登陸");
-
-
- sinaCt.setOnClickListener(this);
- qzoneCt.setOnClickListener(this);
- tengxunCt.setOnClickListener(this);
- renrenCt.setOnClickListener(this);
-
-
- AbstractWeibo[] weibos = AbstractWeibo.getWeiboList(this);
-
- for(int i = 0;i < weibos.length;i++){
- if (!weibos[i].isValid()) {
- continue;
- }
-
- CheckedTextView ctv = getView(weibos[i]);
- if (ctv != null) {
- ctv.setChecked(true);
-
- String userName = weibos[i].getDb().get("nickname");
- if (userName == null || userName.length() <= 0 || "null".equals(userName)) {
-
- userName = getWeiboName(weibos[i]);
-
- weibos[i].setWeiboActionListener(this);
-
- weibos[i].showUser(null);
- }
- ctv.setText(userName);
- }
- }
- }
-
-
- private CheckedTextView getView(AbstractWeibo weibo) {
- if (weibo == null) {
- return null;
- }
-
- String name = weibo.getName();
- if (name == null) {
- return null;
- }
-
- View v = null;
- if (SinaWeibo.NAME.equals(name)) {
- v = findViewById(R.id.ctvSw);
- }
- else if (TencentWeibo.NAME.equals(name)) {
- v = findViewById(R.id.ctvTc);
- }
- else if (Renren.NAME.equals(name)) {
- v = findViewById(R.id.ctvRr);
- }
- else if (QZone.NAME.equals(name)) {
- v = findViewById(R.id.ctvQz);
- }
-
- if (v == null) {
- return null;
- }
-
- if (! (v instanceof CheckedTextView)) {
- return null;
- }
-
- return (CheckedTextView) v;
- }
-
-
- private String getWeiboName(AbstractWeibo weibo) {
- if (weibo == null) {
- return null;
- }
-
- String name = weibo.getName();
- if (name == null) {
- return null;
- }
-
- int res = 0;
- if (SinaWeibo.NAME.equals(name)) {
- res = R.string.sinaweibo;
- }
- else if (TencentWeibo.NAME.equals(name)) {
- res = R.string.tencentweibo;
- }
- else if (Renren.NAME.equals(name)) {
- res = R.string.renren;
- }
- else if (QZone.NAME.equals(name)) {
- res = R.string.qzone;
- }
-
- if (res == 0) {
- return name;
- }
- return this.getResources().getString(res);
- }
-
-
- @Override
- public void onClick(View v) {
- AbstractWeibo weibo = getWeibo(v.getId());
-
- CheckedTextView ctv = (CheckedTextView) v;
- if (weibo == null) {
- ctv.setChecked(false);
- ctv.setText(R.string.not_yet_authorized);
- return;
- }
-
- if (weibo.isValid()) {
- weibo.removeAccount();
- ctv.setChecked(false);
- ctv.setText(R.string.not_yet_authorized);
- return;
- }
-
- weibo.setWeiboActionListener(this);
- weibo.showUser(null);
- }
-
-
- private AbstractWeibo getWeibo(int vid) {
- String name = null;
- switch (vid) {
-
- case R.id.ctvSw:
- name = SinaWeibo.NAME;
- break;
-
- case R.id.ctvTc:
- name = TencentWeibo.NAME;
- break;
-
- case R.id.ctvRr:
- name = Renren.NAME;
- break;
-
- case R.id.ctvQz:
- name = QZone.NAME;
- break;
- }
-
- if (name != null) {
- return AbstractWeibo.getWeibo(this, name);
- }
- return null;
- }
-
-
- @Override
- public void onComplete(AbstractWeibo weibo, int action,HashMap<String, Object> res) {
- Message msg = new Message();
- msg.arg1 = 1;
- msg.arg2 = action;
- msg.obj = weibo;
- handler.sendMessage(msg);
- }
-
-
- @Override
- public void onError(AbstractWeibo weibo, int action, Throwable t) {
- t.printStackTrace();
-
- Message msg = new Message();
- msg.arg1 = 2;
- msg.arg2 = action;
- msg.obj = weibo;
- handler.sendMessage(msg);
- }
-
-
- @Override
- public void onCancel(AbstractWeibo weibo, int action) {
- Message msg = new Message();
- msg.arg1 = 3;
- msg.arg2 = action;
- msg.obj = weibo;
- handler.sendMessage(msg);
- }
-
-
- @Override
- public boolean handleMessage(Message msg) {
- AbstractWeibo weibo = (AbstractWeibo) msg.obj;
- String text = MainActivity.actionToString(msg.arg2);
-
- switch (msg.arg1) {
- case 1: {
- text = weibo.getName() + " completed at " + text;
- Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
- }
- break;
- case 2: {
- text = weibo.getName() + " caught error at " + text;
- Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
- return false;
- }
- case 3: {
- text = weibo.getName() + " canceled at " + text;
- Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
- return false;
- }
- }
-
- CheckedTextView ctv = getView(weibo);
- if (ctv != null) {
- ctv.setChecked(true);
- String userName = weibo.getDb().get("nickname");
- if (userName == null || userName.length() <= 0
- || "null".equals(userName)) {
- userName = getWeiboName(weibo);
- }
- ctv.setText(userName);
- }
- return false;
- }
- }
十、獲取用戶信息界面,GetInfoActivity.java:
- package com.yangyu.activity;
-
- import java.util.HashMap;
-
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Handler.Callback;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.Toast;
- import cn.sharesdk.framework.AbstractWeibo;
- import cn.sharesdk.framework.TitleLayout;
- import cn.sharesdk.framework.WeiboActionListener;
- import cn.sharesdk.renren.Renren;
- import cn.sharesdk.sina.weibo.SinaWeibo;
- import cn.sharesdk.tencent.qzone.QZone;
- import cn.sharesdk.tencent.weibo.TencentWeibo;
-
- import com.yangyu.mysharethings.R;
-
- public class GetInforActivity extends Activity implements Callback, OnClickListener, WeiboActionListener {
-
-
- private TitleLayout llTitle;
-
- private Button sinaBt,renrenBt,qzoneBt,tengxunBt;
-
- private Handler handler;
-
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- handler = new Handler(this);
-
- setContentView(R.layout.activity_userinfo);
-
- initView();
-
- initData();
-
- }
-
-
- private void initView(){
-
- llTitle = (TitleLayout) findViewById(R.id.llTitle);
-
-
- sinaBt = (Button) findViewById(R.id.btnSw);
- renrenBt = (Button) findViewById(R.id.btnRr);
- qzoneBt = (Button) findViewById(R.id.btnQz);
- tengxunBt = (Button) findViewById(R.id.btnTc);
-
-
- }
-
-
- private void initData(){
-
- llTitle.getBtnBack().setOnClickListener(this);
-
- llTitle.getTvTitle().setText(R.string.get_my_info);
-
-
- sinaBt.setOnClickListener(this);
- renrenBt.setOnClickListener(this);
- qzoneBt.setOnClickListener(this);
- tengxunBt.setOnClickListener(this);
- }
-
-
- @Override
- public void onClick(View v) {
- if (v.equals(llTitle.getBtnBack())) {
- finish();
- return;
- }
-
- String name = null;
-
- switch (v.getId()) {
- case R.id.btnSw:
- name = SinaWeibo.NAME;
- break;
- case R.id.btnTc:
- name = TencentWeibo.NAME;
- break;
- case R.id.btnRr:
- name = Renren.NAME;
- break;
- case R.id.btnQz:
- name = QZone.NAME;
- break;
- }
-
- if (name != null) {
- AbstractWeibo weibo = AbstractWeibo.getWeibo(this, name);
- weibo.setWeiboActionListener(this);
- String account = null;
-
- weibo.showUser(account);
- }
- }
-
- public void onComplete(AbstractWeibo weibo, int action,HashMap<String, Object> res) {
- Message msg = new Message();
- msg.arg1 = 1;
- msg.arg2 = action;
- msg.obj = weibo;
- handler.sendMessage(msg);
-
- Message msg2 = new Message();
- msg2.what = 1;
- JsonUtils ju = new JsonUtils();
- String json = ju.fromHashMap(res);
- msg2.obj = ju.format(json);
- handler.sendMessage(msg2);
- }
-
- public void onError(AbstractWeibo weibo, int action, Throwable t) {
- t.printStackTrace();
-
- Message msg = new Message();
- msg.arg1 = 2;
- msg.arg2 = action;
- msg.obj = weibo;
- handler.sendMessage(msg);
- }
-
- public void onCancel(AbstractWeibo weibo, int action) {
- Message msg = new Message();
- msg.arg1 = 3;
- msg.arg2 = action;
- msg.obj = weibo;
- handler.sendMessage(msg);
- }
-
-
- public boolean handleMessage(Message msg) {
- switch(msg.what) {
- case 1: {
- Intent i = new Intent(this, ShowInforActivity.class);
- i.putExtra("data", String.valueOf(msg.obj));
- startActivity(i);
- }
- break;
- default: {
- AbstractWeibo weibo = (AbstractWeibo) msg.obj;
- String text = MainActivity.actionToString(msg.arg2);
- switch (msg.arg1) {
- case 1: {
- text = weibo.getName() + " completed at " + text;
- }
- break;
- case 2: {
- text = weibo.getName() + " caught error at " + text;
- }
- break;
- case 3: {
- text = weibo.getName() + " canceled at " + text;
- }
- break;
- }
-
- Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
- }
- break;
- }
- return false;
- }
-
-
- }
十一、顯示用戶信息界面,ShowInfoActivity.java:
- package com.yangyu.activity;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.TextView;
- import cn.sharesdk.framework.TitleLayout;
-
- import com.yangyu.mysharethings.R;
-
- public class ShowInforActivity extends Activity implements OnClickListener {
- private TitleLayout llTitle;
-
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_show_userinfo);
-
- llTitle = (TitleLayout) findViewById(R.id.llTitle);
- llTitle.getBtnBack().setOnClickListener(this);
- llTitle.getTvTitle().setText("用戶資料");
-
- TextView tvJson = (TextView) findViewById(R.id.tvJson);
- tvJson.setText(getIntent().getStringExtra("data"));
- }
-
- @Override
- public void onClick(View v) {
- if (v.equals(llTitle.getBtnBack())) {
- finish();
- }
- }
-
- }
十二、這裏還定義了一個Json解析類去讀取受權用戶的信息,JsonUtils.java:
- package com.yangyu.activity;
-
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map.Entry;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
-
- public class JsonUtils {
-
-
- public HashMap<String, Object> fromJson(String jsonStr) {
- try {
- if (jsonStr.startsWith("[")
- && jsonStr.endsWith("]")) {
- jsonStr = "{\"fakelist\":" + jsonStr + "}";
- }
-
- JSONObject json = new JSONObject(jsonStr);
- return fromJson(json);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return new HashMap<String, Object>();
- }
-
- private HashMap<String, Object> fromJson(JSONObject json) throws JSONException {
- HashMap<String, Object> map = new HashMap<String, Object>();
- @SuppressWarnings("unchecked")
- Iterator<String> iKey = json.keys();
- while(iKey.hasNext()) {
- String key = iKey.next();
- Object value = json.opt(key);
- if (JSONObject.NULL.equals(value)) {
- value = null;
- }
- if (value != null) {
- if (value instanceof JSONObject) {
- value = fromJson((JSONObject)value);
- }
- else if (value instanceof JSONArray) {
- value = fromJson((JSONArray)value);
- }
- map.put(key, value);
- }
- }
- return map;
- }
-
- private ArrayList<Object> fromJson(JSONArray array)
- throws JSONException {
- ArrayList<Object> list = new ArrayList<Object>();
- for (int i = 0, size = array.length(); i < size; i++) {
- Object value = array.opt(i);
- if (value instanceof JSONObject) {
- value = fromJson((JSONObject)value);
- }
- else if (value instanceof JSONArray) {
- value = fromJson((JSONArray)value);
- }
- list.add(value);
- }
- return list;
- }
-
-
- public String fromHashMap(HashMap<String, Object> map) {
- try {
- return getJSONObject(map).toString();
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return "";
- }
-
- @SuppressWarnings("unchecked")
- private JSONObject getJSONObject(HashMap<String, Object> map)
- throws JSONException {
- JSONObject json = new JSONObject();
- for (Entry<String, Object> entry : map.entrySet()) {
- Object value = entry.getValue();
- if (value instanceof HashMap<?, ?>) {
- value = getJSONObject((HashMap<String, Object>)value);
- }
- else if (value instanceof ArrayList<?>) {
- value = getJSONArray((ArrayList<Object>)value);
- }
- json.put(entry.getKey(), value);
- }
- return json;
- }
-
- @SuppressWarnings("unchecked")
- private JSONArray getJSONArray(ArrayList<Object> list)
- throws JSONException {
- JSONArray array = new JSONArray();
- for (Object value : list) {
- if (value instanceof HashMap<?, ?>) {
- value = getJSONObject((HashMap<String, Object>)value);
- }
- else if (value instanceof ArrayList<?>) {
- value = getJSONArray((ArrayList<Object>)value);
- }
- array.put(value);
- }
- return array;
- }
-
-
- public String format(String jsonStr) {
- try {
- return format("", fromJson(jsonStr));
- } catch (Throwable t) {
- t.printStackTrace();
- }
- return "";
- }
-
- @SuppressWarnings("unchecked")
- private String format(String sepStr, HashMap<String, Object> map) {
- StringBuffer sb = new StringBuffer();
- sb.append("{\n");
- String mySepStr = sepStr + "\t";
- int i = 0;
- for (Entry<String, Object> entry : map.entrySet()) {
- if (i > 0) {
- sb.append(",\n");
- }
- sb.append(mySepStr).append('\"').append(entry.getKey()).append("\":");
- Object value = entry.getValue();
- if (value instanceof HashMap<?, ?>) {
- sb.append(format(mySepStr, (HashMap<String, Object>)value));
- }
- else if (value instanceof ArrayList<?>) {
- sb.append(format(mySepStr, (ArrayList<Object>)value));
- }
- else if (value instanceof String) {
- sb.append('\"').append(value).append('\"');
- }
- else {
- sb.append(value);
- }
- i++;
- }
- sb.append('\n').append(sepStr).append('}');
- return sb.toString();
- }
-
- @SuppressWarnings("unchecked")
- private String format(String sepStr, ArrayList<Object> list) {
- StringBuffer sb = new StringBuffer();
- sb.append("[\n");
- String mySepStr = sepStr + "\t";
- int i = 0;
- for (Object value : list) {
- if (i > 0) {
- sb.append(",\n");
- }
- sb.append(mySepStr);
- if (value instanceof HashMap<?, ?>) {
- sb.append(format(mySepStr, (HashMap<String, Object>)value));
- }
- else if (value instanceof ArrayList<?>) {
- sb.append(format(mySepStr, (ArrayList<Object>)value));
- }
- else if (value instanceof String) {
- sb.append('\"').append(value).append('\"');
- }
- else {
- sb.append(value);
- }
- i++;
- }
- sb.append('\n').append(sepStr).append(']');
- return sb.toString();
- }
-
- }
講到這裏關於這一篇的內容就差很少已經講完了,下一篇是關於微信開放平臺的受權以及分享,由於微信平臺不一樣於其它第三方平臺,實現起來稍微複雜一點,因此博主打算在下一篇的文章中詳細講解。這個下一篇文章估計要等到三天後了吧,博主和女朋友早就商量好趁着三天小長假出去散散心了,在這裏祝你們端午節快樂!博主將會長期堅持更新關於Android、Java、Cocos2d-x、Unity3d等各個不一樣知識領域的實例講解和開發!但願你們繼續支持!
源碼下載地址