在公司最近的一個項目中,須要實現一鍵分享功能,在這裏我使用的是第三方平臺ShareSDK,將使用經驗與你們分享html
先看效果圖java
主界面android
分享界面git
因爲第一次使用,因此須要先進行新浪受權,受權界面web
分享結果圖片api
下面開始介紹如何使用ShareSDK實現微博的分享功能(其餘平臺的相似)微信
首先看一下項目的結構圖網絡
shareSDK傳送門app
在使用shareSDK以前,咱們須要先到新浪微博的開放平臺進行註冊,得到appkey以及其餘的信息ide
新浪微博開放平臺傳送門
下面圖片中劃掉的部分是要重點關注的
特別須要注意的是,下面的回調網址必須填寫,並且在代碼中有涉及,使用默認的便可
至此,開發以前的準備工做已經作好了,下面仍是貼代碼
首先看一下佈局文件代碼,很簡單,只有一個按鈕
<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
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, 0, new 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
<?xml version="1.0" encoding="utf-8"?> 02.<DevInfor> 03. 04.<!-- 05.說明: 06. 07.一、表格中的第一項 08.<ShareSDK 09.AppKey="api20" /> 10.是必須的,其中的AppKey是您在ShareSDK上註冊的開發者賬號的AppKey 11. 12.二、全部集成到您項目的平臺都應該爲其在表格中填寫相對應的開發者信息,以新浪微博爲例: 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
<?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>