Android进阶之使用第三方平台ShareSDK实现新浪微博的一键分享功能

来源:互联网 发布:做淘宝怎么跟快递合作 编辑:程序博客网 时间:2024/03/29 23:59



http://www.it165.net/pro/html/201402/9510.html

http://www.it165.net/pro/html/201402/9510.html

http://www.it165.net/pro/html/201402/9510.html

http://www.it165.net/pro/html/201402/9510.html




Android进阶之使用第三方平台ShareSDK实现新浪微博的一键分享功能

作者:  发布日期:2014-02-21 20:37:59
我来说两句(0)
Tag标签:Android  进阶  使用  
  • 在公司最近的一个项目中,需要实现一键分享功能,在这里我使用的是第三方平台ShareSDK,将使用经验与大家分享

    先看效果图

    主界面

    \

    分享界面

    \

    由于第一次使用,所以需要先进行新浪授权,授权界面

    \

    分享结果图片

    \

    下面开始介绍如何使用ShareSDK实现微博的分享功能(其他平台的类似)

    首先看一下项目的结构图

    \

    shareSDK传送门

    在使用shareSDK之前,我们需要先到新浪微博的开放平台进行注册,获得appkey以及其他的信息

    新浪微博开放平台传送门

    下面图片中划掉的部分是要重点关注的

    \

    特别需要注意的是,下面的回调网址必须填写,而且在代码中有涉及,使用默认的即可

    \

    至此,开发之前的准备工作已经做好了,下面还是贴代码

    首先看一下布局文件代码,很简单,只有一个按钮

     

    view sourceprint?
    01.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    02.xmlns:tools="http://schemas.android.com/tools"
    03.android:layout_width="match_parent"
    04.android:layout_height="match_parent"
    05.android:gravity="center_vertical" >
    06. 
    07.<Button
    08.android:onClick="click"
    09.android:layout_width="match_parent"
    10.android:layout_height="wrap_content"
    11.android:text="一键快捷分享" />
    12. 
    13.</LinearLayout>

    MainActivity.java

     

     

    view sourceprint?
    001.package com.heli17.weiboonekeylogin;
    002. 
    003.import java.io.File;
    004.import java.io.FileOutputStream;
    005.import java.util.HashMap;
    006. 
    007.import android.app.Activity;
    008.import android.app.Notification;
    009.import android.app.NotificationManager;
    010.import android.app.PendingIntent;
    011.import android.content.Context;
    012.import android.content.Intent;
    013.import android.graphics.Bitmap;
    014.import android.graphics.Bitmap.CompressFormat;
    015.import android.graphics.BitmapFactory;
    016.import android.os.Bundle;
    017.import android.os.Environment;
    018.import android.os.Handler.Callback;
    019.import android.os.Message;
    020.import android.view.View;
    021.import android.widget.Toast;
    022.import cn.sharesdk.framework.Platform;
    023.import cn.sharesdk.framework.PlatformActionListener;
    024.import cn.sharesdk.framework.ShareSDK;
    025.import cn.sharesdk.framework.utils.UIHandler;
    026.import cn.sharesdk.onekeyshare.OnekeyShare;
    027. 
    028.public class MainActivity extends Activity implements PlatformActionListener,
    029.Callback {
    030. 
    031.private static final int MSG_TOAST = 1;
    032.private static final int MSG_ACTION_CCALLBACK = 2;
    033.private static final int MSG_CANCEL_NOTIFY = 3;
    034. 
    035.// sdcard中的图片名称
    036.private static final String FILE_NAME = "/share_pic.jpg";
    037.public static String TEST_IMAGE;
    038. 
    039.@Override
    040.public boolean handleMessage(Message msg) {
    041.switch (msg.what) {
    042.case MSG_TOAST: {
    043.String text = String.valueOf(msg.obj);
    044.Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
    045.}
    046.break;
    047.case MSG_ACTION_CCALLBACK: {
    048.switch (msg.arg1) {
    049.case 1// 成功后发送Notification
    050.showNotification(2000"分享完成");
    051.break;
    052.case 2// 失败后发送Notification
    053.showNotification(2000"分享失败");
    054.break;
    055.case 3// 取消
    056.showNotification(2000"取消分享");
    057.break;
    058.}
    059.}
    060.break;
    061.case MSG_CANCEL_NOTIFY:
    062.NotificationManager nm = (NotificationManager) msg.obj;
    063.if (nm != null) {
    064.nm.cancel(msg.arg1);
    065.}
    066.break;
    067.}
    068.return false;
    069.}
    070. 
    071.@Override
    072.protected void onCreate(Bundle savedInstanceState) {
    073.super.onCreate(savedInstanceState);
    074.setContentView(R.layout.activity_main);
    075.// 初始化ShareSDK
    076.ShareSDK.initSDK(this);
    077.// 初始化图片路径
    078.new Thread() {
    079.public void run() {
    080.initImagePath();
    081.}
    082.}.start();
    083.}
    084. 
    085.//一键分享的点击事件
    086.public void click(View v) {
    087.//实例化一个OnekeyShare对象
    088.OnekeyShare oks = new OnekeyShare();
    089.//设置Notification的显示图标和显示文字
    090.oks.setNotification(R.drawable.ic_launcher, "ShareSDK demo");
    091.//设置短信地址或者是邮箱地址,如果没有可以不设置
    092.oks.setAddress("12345678901");
    093.//分享内容的标题
    094.oks.setTitle("分享内容的标题");
    095.//标题对应的网址,如果没有可以不设置
    096.oks.setTitleUrl("http://www.17heli.com");
    097.//设置分享的文本内容
    098.oks.setText("分享的文本内容");
    099.//设置分享照片的本地路径,如果没有可以不设置
    100.oks.setImagePath(MainActivity.TEST_IMAGE);
    101.//设置分享照片的url地址,如果没有可以不设置
    102.oks.setImageUrl("http://img.appgo.cn/imgs/sharesdk/content/2013/07/25/1374723172663.jpg");
    103.//微信和易信的分享的网络连接,如果没有可以不设置
    104.oks.setUrl("http://sharesdk.cn");
    105.//人人平台特有的评论字段,如果没有可以不设置
    106.oks.setComment("comment");
    107.//程序的名称或者是站点名称
    108.oks.setSite("site");
    109.//程序的名称或者是站点名称的链接地址
    110.oks.setSiteUrl("http://www.baidu.com");
    111.//设置纬度
    112.oks.setLatitude(23.122619f);
    113.//设置精度
    114.oks.setLongitude(113.372338f);
    115.//设置是否是直接分享
    116.oks.setSilent(false);
    117.//显示
    118.oks.show(MainActivity.this);
    119.}
    120. 
    121.private void initImagePath() {
    122.try {
    123.if (Environment.MEDIA_MOUNTED.equals(Environment
    124..getExternalStorageState())
    125.&& Environment.getExternalStorageDirectory().exists()) {
    126.TEST_IMAGE = Environment.getExternalStorageDirectory()
    127..getAbsolutePath() + FILE_NAME;
    128.else {
    129.TEST_IMAGE = getApplication().getFilesDir().getAbsolutePath()
    130.+ FILE_NAME;
    131.}
    132.// 创建图片文件夹
    133.File file = new File(TEST_IMAGE);
    134.if (!file.exists()) {
    135.file.createNewFile();
    136.Bitmap pic = BitmapFactory.decodeResource(getResources(),
    137.R.drawable.pic);
    138.FileOutputStream fos = new FileOutputStream(file);
    139.pic.compress(CompressFormat.JPEG, 100, fos);
    140.fos.flush();
    141.fos.close();
    142.}
    143.catch (Throwable t) {
    144.t.printStackTrace();
    145.TEST_IMAGE = null;
    146.}
    147.}
    148. 
    149.@Override
    150.protected void onDestroy() {
    151.super.onDestroy();
    152.// 在Activity中停止ShareSDK
    153.ShareSDK.stopSDK(this);
    154.}
    155. 
    156.// 取消后的回调方法
    157.@Override
    158.public void onCancel(Platform platform, int action) {
    159.Message msg = new Message();
    160.msg.what = MSG_ACTION_CCALLBACK;
    161.msg.arg1 = 3;
    162.msg.arg2 = action;
    163.msg.obj = platform;
    164.UIHandler.sendMessage(msg, this);
    165.}
    166. 
    167.// 完成后的回调方法
    168.@Override
    169.public void onComplete(Platform platform, int action,
    170.HashMap<String, Object> arg2) {
    171.Message msg = new Message();
    172.msg.what = MSG_ACTION_CCALLBACK;
    173.msg.arg1 = 1;
    174.msg.arg2 = action;
    175.msg.obj = platform;
    176.UIHandler.sendMessage(msg, this);
    177.}
    178. 
    179.// 出错后的回调方法
    180.@Override
    181.public void onError(Platform platform, int action, Throwable t) {
    182.t.printStackTrace();
    183.Message msg = new Message();
    184.msg.what = MSG_ACTION_CCALLBACK;
    185.msg.arg1 = 2;
    186.msg.arg2 = action;
    187.msg.obj = t;
    188.UIHandler.sendMessage(msg, this);
    189.}
    190. 
    191.// 根据传入的参数显示一个Notification
    192.@SuppressWarnings("deprecation")
    193.private void showNotification(long cancelTime, String text) {
    194.try {
    195.Context app = getApplicationContext();
    196.NotificationManager nm = (NotificationManager) app
    197..getSystemService(Context.NOTIFICATION_SERVICE);
    198.final int id = Integer.MAX_VALUE / 13 1;
    199.nm.cancel(id);
    200.long when = System.currentTimeMillis();
    201.Notification notification = new Notification(
    202.R.drawable.ic_launcher, text, when);
    203.PendingIntent pi = PendingIntent.getActivity(app, 0new Intent(),
    204.0);
    205.notification.setLatestEventInfo(app, "sharesdk test", text, pi);
    206.notification.flags = Notification.FLAG_AUTO_CANCEL;
    207.nm.notify(id, notification);
    208. 
    209.if (cancelTime > 0) {
    210.Message msg = new Message();
    211.msg.what = MSG_CANCEL_NOTIFY;
    212.msg.obj = nm;
    213.msg.arg1 = id;
    214.UIHandler.sendMessageDelayed(msg, cancelTime, this);
    215.}
    216.catch (Exception e) {
    217.e.printStackTrace();
    218.}
    219.}
    220. 
    221.}

    ShareSDK.xml

     

    view sourceprint?
    01.<?xml version="1.0" encoding="utf-8"?>
    02.<DevInfor>
    03. 
    04.<!--
    05.说明:
    06. 
    07.1、表格中的第一项
    08.<ShareSDK
    09.AppKey="api20" />
    10.是必须的,其中的AppKey是您在ShareSDK上注册的开发者帐号的AppKey
    11. 
    12.2、所有集成到您项目的平台都应该为其在表格中填写相对应的开发者信息,以新浪微博为例:
    13.<SinaWeibo
    14.Id="1"
    15.SortId="1"
    16.AppKey="568898243"
    17.AppSecret="38a4f8204cc784f81f9f0daaf31e02e3"
    18.RedirectUrl="http://www.sharesdk.cn"
    19.Enable="true" />
    20.其中的SortId是此平台在分享列表中的位置,由开发者自行定义,可以是任何整型数字,数值越大
    21.越靠后AppKey、AppSecret和RedirectUrl是您在新浪微博上注册开发者信息和应用后得到的信息
    22.Id是一个保留的识别符,整型,ShareSDK不使用此字段,供您在自己的项目中当作平台的识别符。
    23.Enable字段表示此平台是否有效,布尔值,默认为true,如果Enable为false,即便平台的jar包
    24.已经添加到应用中,平台实例依然不可获取。
    25. 
    26.各个平台注册应用信息的地址如下:
    27.新浪微博                 http://open.weibo.com
    28.腾讯微博                 http://dev.t.qq.com
    29.<a href="http://www.it165.net/qq/qqkj/" target="_blank" class="keylink">QQ空间</a>                     http://connect.<;a href="http://www.it165.net/qq/" target="_blank" class="keylink">qq</a>.com/intro/login/
    30.微信好友                 http://open.weixin.<a href="http://www.it165.net/qq/" target="_blank" class="keylink">qq</a>.com
    31.Facebook      https://developers.facebook.com
    32.Twitter       https://dev.twitter.com
    33.人人网                      http://dev.renren.com
    34.开心网                      http://open.kaixin001.com
    35.搜狐微博                 http://open.t.sohu.com
    36.网易微博                 http://open.t.163.com
    37.豆瓣                           http://developers.douban.com
    38.有道云笔记            http://note.youdao.com/open/developguide.html#app
    39.印象笔记                 https://dev.evernote.com/
    40.Linkedin      https://www.linkedin.com/secure/developer?newapp=
    41.FourSquare    https://developer.foursquare.com/
    42.搜狐随身看            https://open.sohu.com/
    43.Flickr        http://www.flickr.com/services/
    44.Pinterest     http://developers.pinterest.com/
    45.Tumblr        http://www.tumblr.com/developers
    46.Dropbox       https://www.dropbox.com/developers
    47.Instagram     http://instagram.com/developer#
    48.VKontakte     http://vk.com/dev
    49.-->
    50. 
    51.<ShareSDK AppKey="13881da34ebe" /> <!-- 修改成你在sharesdk后台注册的应用的appkey" -->
    52. 
    53.<SinaWeibo
    54.AppKey="5555572"
    55.AppSecret="5ae6d40aac6e7c0d7d84715540a30d71"
    56.Enable="true"
    57.Id="1"
    58.RedirectUrl="https://api.weibo.com/oauth4/default.html"
    59.SortId="1" />
    60. 
    61.</DevInfor>


     

    清单文件Mainfest.xml

     

     

    view sourceprint?
    01.<?xml version="1.0" encoding="utf-8"?>
    02.<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    03.package="com.heli17.weiboonekeylogin"
    04.android:versionCode="1"
    05.android:versionName="1.0" >
    06. 
    07.<uses-sdk
    08.android:minSdkVersion="8"
    09.android:targetSdkVersion="19" />
    10.<!-- 需要的权限注册 -->
    11.<uses-permission android:name="android.permission.GET_TASKS" />
    12.<uses-permission android:name="android.permission.INTERNET" />
    13.<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    14.<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    15.<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    16.<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    17.<uses-permission android:name="android.permission.READ_PHONE_STATE" />
    18.<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    19.<uses-permission android:name="android.permission.GET_ACCOUNTS" />
    20. 
    21.<application
    22.android:allowBackup="true"
    23.android:icon="@drawable/ic_launcher"
    24.android:label="@string/app_name" >
    25.<activity
    26.android:name="com.heli17.weiboonekeylogin.MainActivity"
    27.android:label="@string/app_name"
    28.android:theme="@android:style/Theme.Black.NoTitleBar" >
    29.<intent-filter>
    30.<action android:name="android.intent.action.MAIN" />
    31. 
    32.<category android:name="android.intent.category.LAUNCHER" />
    33.</intent-filter>
    34.</activity>
    35.<!-- 这是进行授权页面的注册 -->
    36.<activity
    37.android:name="cn.sharesdk.framework.ShareSDKUIShell"
    38.android:configChanges="keyboardHidden|orientation"
    39.android:screenOrientation="portrait"
    40.android:theme="@android:style/Theme.Translucent.NoTitleBar"
    41.android:windowSoftInputMode="stateHidden|adjustResize" >
    42.<meta-data
    43.android:name="Adapter"
    44.android:value="cn.sharesdk.demo.MyAdapter" />
    45. 
    46.<intent-filter>
    47.<data android:scheme="db-7janx53ilz11gbs" />
    48. 
    49.<action android:name="android.intent.action.VIEW" />
    50. 
    51.<category android:name="android.intent.category.BROWSABLE" />
    52.<category android:name="android.intent.category.DEFAULT" />
    53.</intent-filter>
    54.</activity>
    55.</application>
    56. 
    57.</manifest>

    好了,这样就可以实现新浪微博的一键分享了,如果有什么问题,请留言交流

     

    源代码下载  http://yun.baidu.com/share/link?shareid=1655676811&uk=2805318064




0 0