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

在公司最近的一个项目中,需要实现一键分享功能,在这里我使用的是第三方平台ShareSDK,将使用经验与大家分享

先看效果图

主界面



分享界面




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




分享结果图片



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

首先看一下项目的结构图


shareSDK传送门

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

新浪微博开放平台传送门

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



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



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



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

<LinearLayout 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"
    android:gravity="center_vertical" >

    <Button
        android:onClick="click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="一键快捷分享" />

</LinearLayout>

MainActivity.java

package com.heli17.weiboonekeylogin;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
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.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class MainActivity extends Activity implements PlatformActionListener,
		Callback {

	private static final int MSG_TOAST = 1;
	private static final int MSG_ACTION_CCALLBACK = 2;
	private static final int MSG_CANCEL_NOTIFY = 3;

	// sdcard中的图片名称
	private static final String FILE_NAME = "/share_pic.jpg";
	public static String TEST_IMAGE;

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MSG_TOAST: {
			String text = String.valueOf(msg.obj);
			Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
		}
			break;
		case MSG_ACTION_CCALLBACK: {
			switch (msg.arg1) {
			case 1: // 成功后发送Notification
				showNotification(2000, "分享完成");
				break;
			case 2: // 失败后发送Notification
				showNotification(2000, "分享失败");
				break;
			case 3: // 取消
				showNotification(2000, "取消分享");
				break;
			}
		}
			break;
		case MSG_CANCEL_NOTIFY:
			NotificationManager nm = (NotificationManager) msg.obj;
			if (nm != null) {
				nm.cancel(msg.arg1);
			}
			break;
		}
		return false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 初始化ShareSDK
		ShareSDK.initSDK(this);
		// 初始化图片路径
		new Thread() {
			public void run() {
				initImagePath();
			}
		}.start();
	}
	
	//一键分享的点击事件
	public void click(View v) {
		//实例化一个OnekeyShare对象
		OnekeyShare oks = new OnekeyShare();
		//设置Notification的显示图标和显示文字
		oks.setNotification(R.drawable.ic_launcher, "ShareSDK demo");
		//设置短信地址或者是邮箱地址,如果没有可以不设置
		oks.setAddress("12345678901");
		//分享内容的标题
		oks.setTitle("分享内容的标题");
		//标题对应的网址,如果没有可以不设置
		oks.setTitleUrl("http://www.17heli.com");
		//设置分享的文本内容
		oks.setText("分享的文本内容");
		//设置分享照片的本地路径,如果没有可以不设置
		oks.setImagePath(MainActivity.TEST_IMAGE);
		//设置分享照片的url地址,如果没有可以不设置
		oks.setImageUrl("http://img.appgo.cn/imgs/sharesdk/content/2013/07/25/1374723172663.jpg");
		//微信和易信的分享的网络连接,如果没有可以不设置
		oks.setUrl("http://sharesdk.cn");
		//人人平台特有的评论字段,如果没有可以不设置
		oks.setComment("comment");
		//程序的名称或者是站点名称
		oks.setSite("site");
		//程序的名称或者是站点名称的链接地址
		oks.setSiteUrl("http://www.baidu.com");
		//设置纬度
		oks.setLatitude(23.122619f);
		//设置精度
		oks.setLongitude(113.372338f);
		//设置是否是直接分享
		oks.setSilent(false);
		//显示
		oks.show(MainActivity.this);
	}

	private void initImagePath() {
		try {
			if (Environment.MEDIA_MOUNTED.equals(Environment
					.getExternalStorageState())
					&& Environment.getExternalStorageDirectory().exists()) {
				TEST_IMAGE = Environment.getExternalStorageDirectory()
						.getAbsolutePath() + FILE_NAME;
			} else {
				TEST_IMAGE = getApplication().getFilesDir().getAbsolutePath()
						+ FILE_NAME;
			}
			// 创建图片文件夹
			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
	protected void onDestroy() {
		super.onDestroy();
		// 在Activity中停止ShareSDK
		ShareSDK.stopSDK(this);
	}

	// 取消后的回调方法
	@Override
	public void onCancel(Platform platform, int action) {
		Message msg = new Message();
		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 3;
		msg.arg2 = action;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
	}

	// 完成后的回调方法
	@Override
	public void onComplete(Platform platform, int action,
			HashMap<String, Object> arg2) {
		Message msg = new Message();
		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 1;
		msg.arg2 = action;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
	}

	// 出错后的回调方法
	@Override
	public void onError(Platform platform, int action, Throwable t) {
		t.printStackTrace();
		Message msg = new Message();
		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 2;
		msg.arg2 = action;
		msg.obj = t;
		UIHandler.sendMessage(msg, this);
	}

	// 根据传入的参数显示一个Notification
	@SuppressWarnings("deprecation")
	private void showNotification(long cancelTime, String text) {
		try {
			Context app = getApplicationContext();
			NotificationManager nm = (NotificationManager) app
					.getSystemService(Context.NOTIFICATION_SERVICE);
			final int id = Integer.MAX_VALUE / 13 + 1;
			nm.cancel(id);
			long when = System.currentTimeMillis();
			Notification notification = new Notification(
					R.drawable.ic_launcher, text, when);
			PendingIntent pi = PendingIntent.getActivity(app, 0, new Intent(),
					0);
			notification.setLatestEventInfo(app, "sharesdk test", text, pi);
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			nm.notify(id, notification);

			if (cancelTime > 0) {
				Message msg = new Message();
				msg.what = MSG_CANCEL_NOTIFY;
				msg.obj = nm;
				msg.arg1 = id;
				UIHandler.sendMessageDelayed(msg, cancelTime, this);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

ShareSDK.xml

<?xml version="1.0" encoding="utf-8"?>
<DevInfor>

    <!--
    	说明:
    	
    	1、表格中的第一项
    		<ShareSDK 
        		AppKey="api20" />
    	是必须的,其中的AppKey是您在ShareSDK上注册的开发者帐号的AppKey
    	
    	2、所有集成到您项目的平台都应该为其在表格中填写相对应的开发者信息,以新浪微博为例:
    	    <SinaWeibo
                Id="1"
                SortId="1"
                AppKey="568898243"
                AppSecret="38a4f8204cc784f81f9f0daaf31e02e3"
                RedirectUrl="http://www.sharesdk.cn"
                Enable="true" />
    	其中的SortId是此平台在分享列表中的位置,由开发者自行定义,可以是任何整型数字,数值越大
    	越靠后AppKey、AppSecret和RedirectUrl是您在新浪微博上注册开发者信息和应用后得到的信息
    	Id是一个保留的识别符,整型,ShareSDK不使用此字段,供您在自己的项目中当作平台的识别符。
    	Enable字段表示此平台是否有效,布尔值,默认为true,如果Enable为false,即便平台的jar包
    	已经添加到应用中,平台实例依然不可获取。
    	
    	各个平台注册应用信息的地址如下:
			新浪微博                 http://open.weibo.com
			腾讯微博                 http://dev.t.qq.com
			QQ空间                      http://connect.qq.com/intro/login/
			微信好友                 http://open.weixin.qq.com
			Facebook      https://developers.facebook.com
			Twitter       https://dev.twitter.com
			人人网                      http://dev.renren.com
			开心网                      http://open.kaixin001.com
			搜狐微博                 http://open.t.sohu.com
			网易微博                 http://open.t.163.com
			豆瓣                           http://developers.douban.com
			有道云笔记            http://note.youdao.com/open/developguide.html#app
			印象笔记                 https://dev.evernote.com/
			Linkedin      https://www.linkedin.com/secure/developer?newapp=
			FourSquare    https://developer.foursquare.com/
			搜狐随身看            https://open.sohu.com/
			Flickr        http://www.flickr.com/services/
			Pinterest     http://developers.pinterest.com/
			Tumblr        http://www.tumblr.com/developers
			Dropbox       https://www.dropbox.com/developers
			Instagram     http://instagram.com/developer#
			VKontakte     http://vk.com/dev
    -->

    <ShareSDK AppKey="13881da34ebe" /> <!-- 修改成你在sharesdk后台注册的应用的appkey" -->

    <SinaWeibo
        AppKey="5555572"
        AppSecret="5ae6d40aac6e7c0d7d84715540a30d71"
        Enable="true"
        Id="1"
        RedirectUrl="https://api.weibo.com/oauth2/default.html"
        SortId="1" />

</DevInfor>


清单文件Mainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.heli17.weiboonekeylogin"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
	<!-- 需要的权限注册 -->
    <uses-permission android:name="android.permission.GET_TASKS" />
    <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.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.heli17.weiboonekeylogin.MainActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 这是进行授权页面的注册 -->
        <activity
            android:name="cn.sharesdk.framework.ShareSDKUIShell"
            android:configChanges="keyboardHidden|orientation"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:windowSoftInputMode="stateHidden|adjustResize" >
            <meta-data
                android:name="Adapter"
                android:value="cn.sharesdk.demo.MyAdapter" />

            <intent-filter>
                <data android:scheme="db-7janx53ilz11gbs" />

                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

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


源代码下载




原文地址:https://www.cnblogs.com/oversea201405/p/3749558.html