帖子原文URL:
http://blog.csdn.net/yangyu20121224/article/details/9057257
由于公司项目的需要,要实现在项目中使用第三方授权登录以及分享文字和图片等这样的效果,几经波折,查阅了一番资料,做了一个Demo。实现起来的效果还是不错的,不敢独享,决定写一个总结的教程,供大家互相交流、学习和参考,博主只求能和大家共同进步。希望能多多支持!
这篇文章中,我们使用到了Share SDK,它是为iOS、Android、WP8的APP提供社会化功能的一个组件,目前支持如QQ、微信、新浪微博、腾讯微博、开心网、人人网、豆瓣、网易微博、搜狐微博、facebook、twitter、google+等国内外主流社交平台。
一、实现的效果图
主界面效果图 授权登录页面效果图
点击分享按钮弹出分享分享界面 有界面图文分享,分享成功后会发送消息提示
二、项目结构目录
三、编码前的准备工作
1、获取Libs
Libs包含ShareSDK的类库,具体包括三个文件夹,分别是ShareSDK的全局依赖库、ShareSDK当前支持的所有平台工具库和ShareSDK可视化UI的一些支持库。“全局依赖库”是集成ShareSDK的基础,ShareSDK的任何平台都依赖于这个库,而“ShareSDK-GUI”提供的是一个测栏控件和一个快捷分享工具,以方便读者更快速地集成ShareSDK。Libs下载地址
2、导入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包到你的项目中,那么只能手动添加,如下图所示:
四、详细的编码实现
1、ShareSdK使用统一的格式管理你在不同平台上注册的开发者信息。这些信息都存放在项目的“assets/ShareSDKDevInfor.xml”中,ShareSDKDevInfor.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <DevInfor>
- <!--说明:
- 1、表格中的第一项
- <ShareSDK AppKey="api20" />
- 是必须的,其中的AppKey是你在Share SDK上注册的开发者帐号的AppKey
-
- 2、所有集成到你项目的平台都应该为其在表格中填写相对应的开发者信息,以新浪微博为例:
- <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>
2、配置AndroidManifest.xml,不同的集成度需要在AndroidManifest.xml中添加的内容也不一样。但是首先你需要添加下面的权限列表:
- <uses-permissionandroid:name="android.permission.INTERNET"/>
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
- <uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
- <uses-permission android:name="android.permission.WRITE_APN_SETTINGS"/>
- <uses-permissionandroid:name="android.permission.CHANGE_WIFI_STATE"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- <uses-permissionandroid:name="android.permission.READ_PHONE_STATE"/>
这些权限将允许你的项目和ShareSDK获取连接网络的权限、获取你的设备网络状态的权限、实现https安全连接的权限、读取手机设备状态的权限和保存必要配置的权限。一般来说,即便不集成ShareSDK,大部分的项目也都会注册申请这些权限。
注意:大家在加入这个"android.permission.WRITE_APN_SETTINGS"权限的时候,可能有些读者的编译器会报错,博主就遇到了这样的情况,这个是ADT Lint工具的问题。
解决的办法是:依照下面的路径“Window —> Preferences —> android—> lint error checking”打开lint的配置页面,然后去掉页面顶部的两个勾选,之后再clean项目就能处理。如下图所示:
3、其次,为了授权操作可以顺利完成,需要在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包中。
4、添加布局页面,首先是主界面的布局页面,activity_main.xml:
- <RelativeLayoutxmlns: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>
5、用户授权登录的布局页面,activity_auth.xml:
6、获得用户信息布局界面,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>
7、显示用户获得的信息布局界面,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>
8、主界面入口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 MainActivityextends 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"/>
9、帐号授权登录界面,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 AuthActivityextends 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;
- }
- }
10、获取用户信息界面,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 GetInforActivityextends 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;
- }
-
-
- }
11、显示用户信息界面,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 ShowInforActivityextends 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();
- }
- }
-
- }
12、这里还定义了一个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 (valueinstanceof 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 (valueinstanceof 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 (valueinstanceof 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 (valueinstanceof 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 (valueinstanceof 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等各个不同知识领域的实例讲解和开发!希望大家继续支持!
----------------------------------------------------------------
最近弄了下QQ微信微博的登录分享,在这里做一下总结,以下登录分享使用的都是官方的最新SDk。
首先是QQ的登录:
1.第一步肯定是先去开放平台注册应用,这里步骤就不详细说了 http://open.qq.com/
2.将下载好的jar包导入工程,在AndroidManifest文件里面注册SDK里面提供的Activity
<activity
android:name="com.tencent.tauth.AuthActivity"
android:launchMode="singleTask"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tencent自己的AppId" />
</intent-filter>
</activity>
<activity
android:name="com.tencent.connect.common.AssistActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
到这里前期的准备工作就全部做好了
3.首先写一个类实现IUiListener接口作为登录后的回调
public class BaseUiListener implements IUiListener {
@Override
public void onComplete(Object o) {
Toast.makeText(MyFragmentActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(UiError uiError) {
Toast.makeText(MyFragmentActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
Toast.makeText(MyFragmentActivity.this, "取消登录", Toast.LENGTH_SHORT).show();
}
}
4.接下来开始写登录代码了
private Tencent mTencent;
mTencent = Tencent.createInstance("AppId", this);
if (!mTencent.isSessionValid()) {
mTencent.login(this, "all", myFragmentActivity.baseUiListener);
}
里面的all代表你需要获取的权限
5.重写onActivityResult方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Constants.ACTIVITY_OK) {
if (requestCode == Constants.REQUEST_LOGIN) {
if (baseUiListener != null)
Tencent.onActivityResultData(requestCode, resultCode, data, baseUiListener);
} else if (requestCode == Constants.REQUEST_OLD_SHARE) {
if (shareListener != null)
Tencent.onActivityResultData(requestCode, resultCode, data, shareListener);
}
}
}
里面包括了分享的回调,登录到这就全部做好了,但是一般登录后都需要获取用户信息,只需要将以下代码放在登录成功的回调里面就可以了
if (setDataListener != null) {
try {
JSONObject data = (JSONObject) o;
String openID = data.getString("openid");
String accessToken = data.getString("access_token");
String expires = data.getString("expires_in");
mTencent.setOpenId(openID);
mTencent.setAccessToken(accessToken, expires);
UserInfo userInfo = new UserInfo(getActivity(), mTencent.getQQToken());
userInfo.getUserInfo(iUiListener);
} catch (JSONException e) {
e.printStackTrace();
}
}
里面的iUiListener是获取用户信息的回调
private IUiListener iUiListener = new IUiListener() {
@Override
public void onComplete(Object o) {
if (o != null) {
Toast.makeText(getActivity(), o.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "获取信息为空", Toast.LENGTH_LONG).show();
}
}
@Override
public void onError(UiError uiError) {
Toast.makeText(getActivity(), "获取信息失败", Toast.LENGTH_LONG).show();
}
@Override
public void onCancel() {
}
};
QQ分享
QQ的分享比较简单,直接贴代码
private void share() {
Bundle bundle = new Bundle();
//这条分享消息被好友点击后的跳转URL。
bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://connect.qq.com/");
//分享的标题。注:PARAM_TITLE、PARAM_IMAGE_URL、PARAM_ SUMMARY不能全为空,最少必须有一个是有值的。
bundle.putString(QQShare.SHARE_TO_QQ_TITLE, "我在测试");
//分享的图片URL
bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
"http://img3.cache.netease.com/photo/0005/2013-03-07/8PBKS8G400BV0005.jpg");
//分享的消息摘要,最长50个字
bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY, "测试");
mTencent.shareToQQ(this, bundle,new ShareListener());
}
public class ShareListener implements IUiListener {
@Override
public void onComplete(Object o) {
Toast.makeText(MyFragmentActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(UiError uiError) {
Toast.makeText(MyFragmentActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
Toast.makeText(MyFragmentActivity.this, "取消分享", Toast.LENGTH_SHORT).show();
}
}
微信登录
由于微信的回调有所不同,所以这里登录分享一起弄,还有微信的登录分享都只能在安装了微信客户端的情况下才能使用
1.第一步同样去注册应用信息 https://open.weixin.qq.com/
2.下载SDk导入工程
3.在你的包名相应目录下新建一个wxapi目录,并在该wxapi目录下新增一个WXEntryActivity类,该类继承自Activity并实现IWXAPIEventHandler接口
4.注册这个Activity
<activity
android:name=".wxapi.WXEntryActivity"
android:exported="true" />
准备工作到这里也就全部做完了
5.接下来贴登录代码
private IWXAPI iwxapi;
iwxapi = WXAPIFactory.createWXAPI(this, "AppId");
if (!iwxapi.isWXAppInstalled()) {
Toast.makeText(getActivity(), "请先安装微信应用", Toast.LENGTH_SHORT).show();
break;
}
iwxapi.registerApp("");
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";//需要的权限范围
req.state = "wechat_sdk_demo_test";
iwxapi.sendReq(req);
6.接下来贴上分享代码
private void weixShare() {
WXWebpageObject wxWebpageObject = new WXWebpageObject();
wxWebpageObject.webpageUrl = "https://www.baidu.com/";
WXMediaMessage message = new WXMediaMessage(wxWebpageObject);
message.title = "百度哦";
message.description = "这是百度";
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a);
message.setThumbImage(bitmap);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = message;
//发送到聊天界面WXSceneSession 发送到朋友圈WXSceneTimeline
req.scene = SendMessageToWX.Req.WXSceneSession;
iwxapi.sendReq(req);
}
7.接下来就是在WXEntryActivity类里面处理的回调,先直接把代码全部贴出
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// handleIntent(intent);
api= WXAPIFactory.createWXAPI(this, "AppId");
api.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp baseResp) {
String result = "";
int type = baseResp.getType();
String typeString = "";
//type=1表示登录,type=2表示分享
if (type==1){
typeString = "登录";
if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
//用户同意
String code = ((SendAuth.Resp) baseResp).code;
Intent goMain = new Intent(this, MyFragmentActivity.class);
goMain.putExtra("code", code);
startActivity(goMain);
}
}else if (type==2){
typeString = "分享";
}
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK:
Log.i("onResp", "调用了WXEntryActivity中的onResp方法");
result = typeString+"成功";
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
result = typeString+"分享";
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
result = typeString+"被服务器拒绝";
break;
default:
result = "未知操作";
break;
}
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
this.finish();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// handleIntent(intent);
api.handleIntent(intent, this);
}
private void handleIntent(Intent intent) {
SendAuth.Resp resp = new SendAuth.Resp(intent.getExtras());
if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
//用户同意
String code = resp.code;
Intent goMain = new Intent(this, MyFragmentActivity.class);
intent.putExtra("code", code);
startActivity(goMain);
}
}
}
这里我一开始使用的是自己写的hanleIntent方法绑定回调,结果发现无法区分产生的回调是登录的回调还是分享的回调,得到的type都是1,所以用了另一种方法。
微信的登录分享到这里就全部解决了
微博
登录
1.首先也一样去注册应用 http://open.weibo.com/
2.因为我现在使用的是studio开发,所以导入jar包的方式有点不同
首先我将
做为model导入工程
然后
就这样导入工程,直接导入jar包也是一样的
studio还需要在工程的main目录下创建一个jniLibs文件放置微博的so文件
到这准备工作完成
3.贴上登录代码
AuthInfo authInfo = new AuthInfo(getActivity(), WeiBoConstants.APP_KEY, WeiBoConstants.REDIRECT_URL, WeiBoConstants.SCOPE);
SsoHandler mSsoHandler = new SsoHandler(getActivity(), authInfo);
mSsoHandler.authorize(new AuthListener());
class AuthListener implements WeiboAuthListener {
@Override
public void onComplete(Bundle bundle) {
Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onWeiboException(WeiboException e) {
Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
Toast.makeText(getActivity(), "取消登录", Toast.LENGTH_SHORT).show();
}
}
这个也需要重写onActivityResult方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Constants.ACTIVITY_OK) {
if (requestCode == Constants.REQUEST_LOGIN) {
if (baseUiListener != null)
Tencent.onActivityResultData(requestCode, resultCode, data, baseUiListener);
} else if (requestCode == Constants.REQUEST_OLD_SHARE) {
if (shareListener != null)
Tencent.onActivityResultData(requestCode, resultCode, data, shareListener);
} else {
if (requestCode == 32973)//这个是微博的requestCode值,不知道为什么没有把它暴露出来
if (mSsoHandler != null) {
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
}
}
登录到这里就做好了,接下来是分享
分享需要在你接收分享回调信息的Activity中加上
<intent-filter>
<action Android:name="com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
例如
<activity android:name=".WeiBoShareActivity" >
<intent-filter>
<action android:name="com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
接下来贴上分享的代码
private IWeiboShareAPI mWeiboShareAPI;
mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, WeiBoConstants.APP_KEY);
//下面这端代码需要放在onCreate里面
if (savedInstanceState != null) {
mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
}
private void weiBoShare() {
mWeiboShareAPI.registerApp();
ImageObject imageObject = new ImageObject();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
imageObject.setImageObject(bitmap);
TextObject textObject = new TextObject();
textObject.text = "https://www.baidu.com/";
WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
weiboMessage.textObject =textObject;
// weiboMessage.mediaObject = imageObject;
SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
request.transaction = String.valueOf(System.currentTimeMillis());
request.multiMessage = weiboMessage;
mWeiboShareAPI.sendRequest(this,request);
}
需要重写onNewIntent方法
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
mWeiboShareAPI.handleWeiboResponse(intent, this);
}
进行分享的Activity实现IWeiboHandler.Response接口
@Override
public void onResponse(BaseResponse baseResponse) {
switch (baseResponse.errCode) {
case WBConstants.ErrorCode.ERR_OK:
Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
break;
case WBConstants.ErrorCode.ERR_CANCEL:
Toast.makeText(this, "取消分享", Toast.LENGTH_SHORT).show();
break;
case WBConstants.ErrorCode.ERR_FAIL:
Toast.makeText(this, "分享失败", Toast.LENGTH_SHORT).show();
break;
}
}
到这里微博分享也就全部搞好了
需要注意的是
public static final String REDIRECT_URL = "http://www.sina.com";
设置的回调页要在
写上,要不让会出现网络错误的情况