Android 社會化分享,你應知道的知識都在這裏

分享,已經成爲了一個app的標配了,由於分享到微信,微博和qq等社交平臺有機會能夠爲本身的app帶來大量的流量,提高app的知名度,這是一個快速而有效的增長app用戶量的途徑,因此分享對一個app來講,分享到微信,微博等社交平臺是何其重要。html

本文爲讀者帶來android分享知識,包括藉助第三方工具和手動實現android分享,首先咱們使用第三方工具來實現,接着再帶你們手動打造android分享。android

第三方分享工具:極光社會化分享(sharesdk)、友盟社會化分享(Ushare)以及在githut上比較流行: ShareSDKShareUtilBiliShareShareLoginLib等等。git

使用極光社會分享到能夠參考這篇文章android集成極光社會化分享攻略,若是你想使用友盟社會化分享工具能夠參考這篇文章Android集成友盟社會化分享功能。這兩篇文章都詳細介紹和實現了社會化分享。這裏就不講解使用極光社會分享和友盟來實現分享了。github

ShareUtil

簡介

ShareUtil是一個綜合性的分享及登陸工具庫,支持微信分享,微博分享,QQ分享,QQ空間分享以及Android系統默認分享,支持微信登陸,微博登陸以及QQ登陸並獲取用戶信息。segmentfault

使用

在app下的build.gradle添加依賴api

免第三方Jar包配置 compile 'me.shaohui.shareutil:shareutil:1.3.8' 手動添加第三方jar compile 'me.shaohui.shareutil:shareutil:1.3.8.no_jar'bash

build.gradle 配置 在defaultConfig節點下增長你的qq id信息 defaultConfig { ....... manifestPlaceholders = [ // 替換成你的qq_id qq_id: "123345678" ] }微信

1)、初始化配置多線程

ShareConfig config = ShareConfig.instance()
                .qqId(QQ_ID)
                .wxId(WX_ID)
                .weiboId(WEIBO_ID)
                // 下面兩個,若是不須要登陸功能,可不填寫
                .weiboRedirectUrl(REDIRECT_URL)
                .wxSecret(WX_ID);
ShareManager.init(config);
複製代碼

2)、使用ShareUtilapp

使用ShareUtil類的api便可輕鬆實現社會化分享。 如:

ShareUtil.shareImage(MainActivity.this, SharePlatform.QQ,
                        "http://shaohui.me/images/avatar.gif", mShareListener);
複製代碼

ShareUtil.shareImage:分享圖片。須要指定分享到那個平臺:

一、SharePlatform.QQ分享到qq;

二、SharePlatform.QZONE分享到qq空間;

三、SharePlatform.WEIBO分享到微博;

四、SharePlatform.WX分享到微信;

五、SharePlatform.WX_TIMELINE分享到朋友圈。

mShareListener是須要設置的回調,來監聽是否分享成功以及取消分享等。

如下代碼是個人activity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String QQ_ID = "your qqid";
    private static final String WX_ID = "your weixinid";
    private static final String WEIBO_ID = "your weibo id";
    private static final String REDIRECT_URL = "your weibo redirecturi";
    private ShareListener mShareListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initShare();
        initView();
        initListener();

    }

    private void initView() {
        this.findViewById(R.id.qq).setOnClickListener(this);
        this.findViewById(R.id.qqzone).setOnClickListener(this);
        this.findViewById(R.id.weibo).setOnClickListener(this);
        this.findViewById(R.id.weixin).setOnClickListener(this);
        this.findViewById(R.id.circle).setOnClickListener(this);
    }

    private void initListener() {
        mShareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
                Toast.makeText(MainActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void shareFailure(Exception e) {
                Toast.makeText(MainActivity.this, "分享失敗", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void shareCancel() {
                Toast.makeText(MainActivity.this, "取消分享", Toast.LENGTH_SHORT).show();

            }
        };
    }

    private void initShare() {

        // init
        ShareConfig config = ShareConfig.instance()
                .qqId(QQ_ID)
                .wxId(WX_ID)
                .weiboId(WEIBO_ID)
                // 下面兩個,若是不須要登陸功能,可不填寫
                .weiboRedirectUrl(REDIRECT_URL)
                .wxSecret(WX_ID);
        ShareManager.init(config);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.qq:
                ShareUtil.shareImage(MainActivity.this, SharePlatform.QQ,
                        "http://shaohui.me/images/avatar.gif", mShareListener);
                break;
            case R.id.qqzone:
                ShareUtil.shareMedia(MainActivity.this, SharePlatform.QZONE, "Title", "summary",
                        "http://www.google.com", "http://shaohui.me/images/avatar.gif",
                        mShareListener);
                break;
            case R.id.weibo:
                ShareUtil.shareImage(MainActivity.this, SharePlatform.WEIBO,
                        "http://shaohui.me/images/avatar.gif", mShareListener);
                break;
            case R.id.weixin:
                ShareUtil.shareMedia(MainActivity.this, SharePlatform.WX, "Title", "summary",
                        "http://www.google.com", "http://shaohui.me/images/avatar.gif",
                        mShareListener);
                break;
            case R.id.circle:
                ShareUtil.shareText(MainActivity.this, SharePlatform.WX_TIMELINE, "測試分享文字",
                        mShareListener);
                break;
            default:
                break;
        }
    }
}
複製代碼

效果圖

ShareSDK

簡介

ShareSDK是社會化分享SDK,包括微信、朋友圈,微博,QQ,QQ空間等渠道分享。

使用

添加依賴

compile ('com.xyzlf.share:sharesdk:0.0.9') { exclude group: 'com.android.support', module: 'appcompat-v7' }

添加依賴以後就能夠正常使用ShareSDK來實現社會化分享了,可是須要注意的是在使用微信分享的須要在包名下編寫一個WXEntryActivity的activity,這是使用ShareSDK工具須要必須須要咱們手動實現的,而WXEntryActivity也是分享到微信時,微信要求咱們要作的事情。該activity必需要在包的名字爲項目包名下,不然出錯。具體能夠參考這篇文章分享SDK系列一:遇到的坑

WXEntryActivity:

/**
 * 這個類是微信回調的類
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, ManifestUtil.getWeixinKey(this), false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {

    }

    @Override
    public void onResp(BaseResp resp) {
        Intent intent = new Intent();
        intent.setAction(ShareConstant.ACTION_WEIXIN_CALLBACK);
        intent.putExtra(ShareConstant.EXTRA_WEIXIN_RESULT, resp.errCode);
        sendBroadcast(intent);
        finish();
    }
}
複製代碼
ShareUtil.showShareDialog調用ShareSDK的分享界面:
public void showShareDialog(View view) {
        ShareEntity testBean = new ShareEntity("我是標題", "我是內容,描述內容。");
        testBean.setUrl("https://www.baidu.com"); //分享連接
        testBean.setImgUrl("https://www.baidu.com/img/bd_logo1.png");
        ShareUtil.showShareDialog(this, testBean, ShareConstant.REQUEST_CODE);
    }
複製代碼
分享函數:

ShareUtil.startShare(this, ShareConstant.SHARE_CHANNEL_QQ, testBean, ShareConstant.REQUEST_CODE);

須要指定分享平臺類型:

一、ShareConstant.SHARE_CHANNEL_QQ分享到qq聊天;

二、ShareConstant.SHARE_CHANNEL_QZONE分享到qq空間;

三、ShareConstant.SHARE_CHANNEL_SINA_WEIBO分享到微博;

四、ShareConstant.SHARE_CHANNEL_WEIXIN_FRIEND分享到微信;

五、ShareConstant.SHARE_CHANNEL_WEIXIN_CIRCLE分享到朋友圈。

須要在onActivityResult作回調處理
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    /**
     * 分享回調處理
     */
    if (requestCode == ShareConstant.REQUEST_CODE) {
        if (data != null) {
            int channel = data.getIntExtra(ShareConstant.EXTRA_SHARE_CHANNEL, -1);
            int status = data.getIntExtra(ShareConstant.EXTRA_SHARE_STATUS, -1);
            onShareCallback(channel, status);
        }
    }
}
複製代碼

activity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ShareEntity testBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        testBean = new ShareEntity("我是標題", "我是內容,描述內容。");
        testBean.setUrl("https://www.baidu.com"); //分享連接
        testBean.setImgUrl("https://www.baidu.com/img/bd_logo1.png");

        findViewById(R.id.share_qq).setOnClickListener(this);
        findViewById(R.id.share_qzone).setOnClickListener(this);
        findViewById(R.id.share_weibo).setOnClickListener(this);
        findViewById(R.id.share_weixin).setOnClickListener(this);

        findViewById(R.id.share_bigimage).setOnClickListener(this);

    }

    /**
     * 分享界面
     */
    public void showShareDialog(View view) {
        ShareEntity testBean = new ShareEntity("我是標題", "我是內容,描述內容。");
        testBean.setUrl("https://www.baidu.com"); //分享連接
        testBean.setImgUrl("https://www.baidu.com/img/bd_logo1.png");
        ShareUtil.showShareDialog(this, testBean, ShareConstant.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 分享回調處理
         */
        if (requestCode == ShareConstant.REQUEST_CODE) {
            if (data != null) {
                int channel = data.getIntExtra(ShareConstant.EXTRA_SHARE_CHANNEL, -1);
                int status = data.getIntExtra(ShareConstant.EXTRA_SHARE_STATUS, -1);
                onShareCallback(channel, status);
            }
        }
    }

    /**
     * 分享回調處理
     * @param channel
     * @param status
     */
    private void onShareCallback(int channel, int status) {
        new ShareCallBack().onShareCallback(channel, status);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.share_qq:
                ShareUtil.startShare(this, ShareConstant.SHARE_CHANNEL_QQ, testBean, ShareConstant.REQUEST_CODE);
                break;
            case R.id.share_qzone:
                ShareUtil.startShare(this, ShareConstant.SHARE_CHANNEL_QZONE, testBean, ShareConstant.REQUEST_CODE);
                break;
            case R.id.share_weibo:
                ShareUtil.startShare(this, ShareConstant.SHARE_CHANNEL_SINA_WEIBO, testBean, ShareConstant.REQUEST_CODE);
                break;
            case R.id.share_weixin:
                ShareUtil.startShare(this, ShareConstant.SHARE_CHANNEL_WEIXIN_FRIEND, testBean, ShareConstant.REQUEST_CODE);
                break;
            case R.id.share_wxcircle:
                ShareUtil.startShare(this, ShareConstant.SHARE_CHANNEL_WEIXIN_CIRCLE, testBean, ShareConstant.REQUEST_CODE);
                break;

            //分享大圖
            case R.id.share_bigimage:
                shareBigImg();
                break;
        }
    }

    /**
     * 分享大圖,大圖分享支持,微信,微信朋友圈,微博,QQ,其餘渠道不支持
     *
     * 分享大圖注意點
     * 一、setShareBigImg爲ture
     * 二、QQ分享大圖,只能是本地圖片
     */
    public void shareBigImg() {
        ShareEntity testBean = new ShareEntity("", "");
        testBean.setShareBigImg(true);
        testBean.setImgUrl("/storage/sdcard0/Android/data/com.xyzlf.share/files/com.xyzlf.share_share_pic.png"); //本地地址

        /** 若是你要分享的圖片是Bitmap,你能夠以下使用 **/
//        Bitmap bitmap = null;
//        String filePath = ShareUtil.saveBitmapToSDCard(this, bitmap);
//        testBean.setImgUrl(filePath);

        int channel = ShareConstant.SHARE_CHANNEL_WEIXIN_FRIEND | ShareConstant.SHARE_CHANNEL_WEIXIN_CIRCLE | ShareConstant.SHARE_CHANNEL_SINA_WEIBO | ShareConstant.SHARE_CHANNEL_QQ;
        ShareUtil.showShareDialog(this, channel, testBean, ShareConstant.REQUEST_CODE);
    }

}
複製代碼

ShareCallBack:

public class ShareCallBack {

    /**
     * @param channel
     * @param status
     */
    public void onShareCallback(int channel, int status) {
        switch (channel) {
            case ShareConstant.SHARE_CHANNEL_WEIXIN_FRIEND:
            case ShareConstant.SHARE_CHANNEL_WEIXIN_CIRCLE:
                onWeixinCallBack(status);
                break;

            case ShareConstant.SHARE_CHANNEL_SINA_WEIBO:
                onWeiboCallBack(status);
                break;

            case ShareConstant.SHARE_CHANNEL_QQ:
                onQQCallBack(status);
                break;

            case ShareConstant.SHARE_CHANNEL_QZONE:
                onQZoneCallBack(status);
                break;

            case ShareConstant.SHARE_CHANNEL_SYSTEM:
                onSystemCallBack(status);
                break;
        }
    }

    /** 沒有取消狀態 **/
    private void onWeixinCallBack(int status) {
        switch (status) {
            /** 成功 **/
            case ShareConstant.SHARE_STATUS_COMPLETE:

                break;
            /** 失敗 **/
            case ShareConstant.SHARE_STATUS_FAILED:

                break;
        }
    }

    /**
     * 如下有成功,失敗,取消三種回調結果
     * @param status
     */
    private void onWeiboCallBack(int status) {
        switch (status) {
            /** 成功 **/
            case ShareConstant.SHARE_STATUS_COMPLETE:

                break;
            /** 失敗 **/
            case ShareConstant.SHARE_STATUS_FAILED:

                break;
            /** 取消 **/
            case ShareConstant.SHARE_STATUS_CANCEL:

                break;
        }
    }

    private void onQQCallBack(int status) {

    }

    private void onQZoneCallBack(int status) {
    }


    /** 系統分享,回調結果沒有實際意義,由於不能知道用戶是否發送短信了,是否發送郵件了 **/
    private void onSystemCallBack(int status) {
    }
    /** 系統分享,回調結果沒有實際意義,由於不能知道用戶是否發送短信了,是否發送郵件了 **/

}
複製代碼

能夠到githut下載demo,詳細瞭解做者如何實現。

ShareLoginLib

簡介

ShareLoginLib是社會化分享工具,幫助開發着實現內容分享到微信、微博和qq社交平臺。

添加依賴

一、在項目外層的build.gradle中添加JitPack倉庫

repositories { // ... maven { url "https://jitpack.io" } }

二、在用到的項目中添加依賴

compile 'com.github.tianzhijiexian:ShareLoginLib:1.3.8'

三、初始化配置

SlConfig cfg = new SlConfig.Builder()
                .debug(false)
                .appName("ShareLoginDemo")
                .picTempFile(null)
                .qq(QQ_APPID, QQ_SCOPE)
                .weiBo(WEIBO_APPID, WEIBO_REDIRECT_URL, WEIBO_SCOPE)
                .weiXin(WEIXIN_APPID, WEIXIN_SECRET)
                .build();

ShareLoginSDK.init(this, cfg);
複製代碼

初始化配置在好在application的onCreate初始化。

public class BaseApplication extends Application {

    private static final String TAG = "Application";

    protected static String QQ_APPID, QQ_SCOPE,
            WEIBO_APPID, WEIBO_SCOPE, WEIBO_REDIRECT_URL,
            WEIXIN_APPID, WEIXIN_SECRET;

    @Override
    public void onCreate() {
        super.onCreate();

        initConstant();

        Log.d(TAG, "onCreate: weixin:" + ShareLoginSDK.isWeiXinInstalled(this));
        Log.d(TAG, "onCreate: weibo:" + ShareLoginSDK.isWeiBoInstalled(this));
        Log.d(TAG, "onCreate: qq:" + ShareLoginSDK.isQQInstalled(this));

        SlConfig cfg = new SlConfig.Builder()
                .debug(false)
                .appName("ShareLoginDemo")
                .picTempFile(null)
                .qq(QQ_APPID, QQ_SCOPE)
                .weiBo(WEIBO_APPID, WEIBO_REDIRECT_URL, WEIBO_SCOPE)
                .weiXin(WEIXIN_APPID, WEIXIN_SECRET)
                .build();

        ShareLoginSDK.init(this, cfg);
    }

    /**
     * 初始化一些常量
     */
    protected void initConstant() {
        QQ_APPID = "xxxxxxxxxxxx";
        QQ_SCOPE = "xxxxxxxxxxxx";
        WEIBO_APPID = "xxxxxxxxxxxx";
        WEIBO_REDIRECT_URL = "xxxxxxxxxxxx";
        WEIXIN_APPID = "xxxxxxxxxxxx";
        WEIXIN_SECRET = "xxxxxxxxxxxx";
        WEIBO_SCOPE = "xxxxxxxxxxxx";
    }
}
複製代碼

四、分享

SsoShareManager.share(this, SsoShareType.QQ_ZONE, mShareContent, mShareListener);

指定分享類型SsoShareType.QQ_ZONE,而且設置分享監聽。

五、登陸

SsoLoginManager.login(this, SsoLoginType.WEIBO, new LoginListener(this, SsoLoginType.WEIBO));

指定登錄類型以及設置登陸監聽。

MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private SsoShareManager.ShareStateListener mShareListener;
    private ShareContent mShareContent;
    private Bitmap thumbBmp = null;
    private Bitmap largeBmp = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        thumbBmp = ((BitmapDrawable) getResources().getDrawable(R.drawable.kale)).getBitmap();
        largeBmp = ((BitmapDrawable) getResources().getDrawable(R.drawable.large)).getBitmap();
        mShareContent = new ShareContentWebPage("title","summary", "http://www.kale.com",thumbBmp, largeBmp);


        this.findViewById(R.id.share_qq).setOnClickListener(this);
        this.findViewById(R.id.share_qqzone).setOnClickListener(this);
        this.findViewById(R.id.share_weibo).setOnClickListener(this);
        this.findViewById(R.id.share_weixin).setOnClickListener(this);
        this.findViewById(R.id.share_circle).setOnClickListener(this);

        this.findViewById(R.id.login_qq).setOnClickListener(this);
        this.findViewById(R.id.login_weibo).setOnClickListener(this);
        this.findViewById(R.id.login_weixin).setOnClickListener(this);


        initListener();
    }

    private void initListener() {

        mShareListener = new SsoShareManager.ShareStateListener(){
            @Override
            public void onSuccess() {
                super.onSuccess(); // must call super
            }

            @Override
            public void onCancel() {
                super.onCancel(); // must call super
            }

            @Override
            public void onError(String msg) {
                super.onError(msg); // must call super
            }
        };

    }

    public void onGotUserInfo(String info, String headImgUrl) {


    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.share_qq:
                SsoShareManager.share(MainActivity.this, SsoShareType.QQ_FRIEND, mShareContent, mShareListener);
                break;
            case R.id.share_qqzone:
                SsoShareManager.share(this, SsoShareType.QQ_ZONE, mShareContent, mShareListener);
                break;
            case R.id.share_weibo:
                SsoShareManager.share(this, SsoShareType.WEIBO_TIME_LINE, mShareContent, mShareListener);
                break;
            case R.id.share_weixin:
                SsoShareManager.share(this, SsoShareType.WEIXIN_FRIEND, mShareContent, mShareListener);
                break;
            case R.id.share_circle:
                SsoShareManager.share(this, SsoShareType.WEIXIN_FRIEND_ZONE, mShareContent, mShareListener);
                break;
            case R.id.login_qq:
                SsoLoginManager.login(this, SsoLoginType.QQ, new LoginListener(this, SsoLoginType.QQ));
                break;
            case R.id.login_weibo:
                SsoLoginManager.login(this, SsoLoginType.WEIBO, new LoginListener(this, SsoLoginType.WEIBO));
                break;
            case R.id.login_weixin:
                SsoLoginManager.login(this, SsoLoginType.WEIXIN, new LoginListener(this, SsoLoginType.WEIXIN));
                break;

            default:
                break;
        }

    }

    public void handResult(String result) {
    }
}
複製代碼

LoginListener:這是做者在demo中的登陸回調接口

class LoginListener extends SsoLoginManager.LoginListener {

    private static final String TAG = "LoginListener";

    private MainActivity activity;

    private
    @SsoLoginType
    String type;

    LoginListener(MainActivity activity, @SsoLoginType String type) {
        this.activity = activity;
        this.type = type;
    }

    @Override
    public void onSuccess(String accessToken, String userId, long expiresIn, String data) {
        super.onSuccess(accessToken, userId, expiresIn, data);
        Log.d(TAG, "accessToken = " + accessToken + "\nuid = " + userId + "\nexpires_in = " + expiresIn);
        loadUserInfo(accessToken, userId);

        String result = "登陸成功";
        Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
        activity.handResult(result);
    }

    @Override
    public void onError(String msg) {
        super.onError(msg);
        String result = "登陸失敗,失敗信息:" + msg;
        Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
        activity.handResult(result);
    }

    @Override
    public void onCancel() {
        super.onCancel();
        String result = "取消登陸";
        Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
        activity.handResult(result);
    }

    /**
     * 加載用戶的我的信息
     */
    private void loadUserInfo(String accessToken, String userId) {
        SsoUserInfoManager.getUserInfo(activity, type, accessToken, userId, new SsoUserInfoManager.UserInfoListener() {
            @Override
            public void onSuccess(@NonNull final OAuthUserInfo userInfo) {
                final String info = " nickname = " + userInfo.nickName + "\n"
                        + " sex = " + userInfo.sex + "\n"
                        + " id = " + userInfo.userId;

                activity.onGotUserInfo(info, userInfo.headImgUrl);
            }

            @Override
            public void onError(String msg) {
                activity.onGotUserInfo(" 出錯了!\n" + msg, null);
            }
        });
    }
}
複製代碼

以上是github上比較流行的分享工具,接下來咱們本身使用微信、微博和qq的分享api手動實現分享功能。

手動實現分享功能

一、到微信、微博和qq的開放平臺,註冊id

二、將分享sdk加入到項目的lib目錄下,微信的sdk也能夠在項目下的build.gradle文件添加依賴:compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:1.0.2'

myshare

mshare

qq分享和qq空間分享

1)、在AndroidManifest.xml中註冊qq的activity

<!-- QQ SDK 須要註冊Activity -->
        <activity
            android:name="com.tencent.tauth.AuthActivity"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:noHistory="true"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
            <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="your qq number"/>
            </intent-filter>
        </activity>
        <activity
            android:name="com.tencent.connect.common.AssistActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>
        <!--<activity-->
            <!--android:name="com.tencent.connect.common.AssistActivity"-->
            <!--android:configChanges="orientation|keyboardHidden"-->
            <!--android:screenOrientation="behind"-->
            <!--android:theme="@android:style/Theme.Translucent.NoTitleBar"/>-->
        <!-- QQ SDK 須要註冊 Activity -->
複製代碼

2)、在onActivityResult處理回調

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
            }
        }

    }
複製代碼

3)、判斷是否安裝qq

/**
     * 是否安裝qq
     *
     * @param context
     * @return
     */
    public boolean isQQAppInstalled(final Context context) {
        try {
            //避免多線程同時調用,致使package manager has died at android.app.ApplicationPackageManager.getPackageInfo
            synchronized (MainActivity.class) {
                PackageInfo pInfo;
                pInfo = context.getPackageManager().getPackageInfo("com.tencent.mobileqq", PackageManager.GET_SERVICES);
                return pInfo == null ? false : true;
            }
        } catch (Exception e) {
            return false;
        }
    }
複製代碼

4)、分享到qq

myshare

回調:

myshare

分享到qq空間

myshare

分享到微博

添加so文件:

myshare

1)、判斷是否安裝微博

myshare

使用微博的api須要經過WeiboShareSDK.createWeiboAPI獲取到IWeiboShareAPI的實例。

2)、受權

myshare

經過mSsoHandler.authorizeClientSso(new MyAuthListener(context,content, path, type, thump));受權,同時設置受權的監聽。若是受權狀態在監聽中回調相應的方法。

3)、微博分享 首先初始化微博的分享消息WeiboMultiMessage; 而後初始化消息請求SendMultiMessageToWeiboRequest; 最後經過mWeiboShareAPI.sendRequest((Activity) context, request)來實現分享到微博。

微信分享

一、微信分享須要在包名爲項目包名.wxapi的包下添加WXEntryActivity。

myshare

二、註冊

<!-- 騰訊sdk -->
<!-- 微信 -->
<activity
    android:name=".wxapi.WXEntryActivity"
    android:exported="true"
    android:label="@string/app_name"
    android:launchMode="singleInstance"
    android:screenOrientation="portrait">
</activity>
複製代碼

三、判斷是否安裝微信客戶端

myshare

四、分享到微信和朋友圈

分享到微信和朋友圈都是使用api.sendReq(req)。 只不過req.scene參數不同:

SendMessageToWX.Req.WXSceneSession:分享到微信;

SendMessageToWX.Req.WXSceneTimeline:分享到朋友圈。

接下來給出各位文件的代碼。

WXEntryActivity:

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, Constant.APPID_WXPAY, true);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }


    @Override
    public void onReq(BaseReq req) {
        switch(req.getType())
        {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                break;
            default:
                finish();
                break;
        }
        Toast.makeText(this, "請求", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResp(BaseResp resp) {
        //微信回調
        String tag = ""+resp.errStr;
        Toast.makeText(this, "onResp:"+tag, Toast.LENGTH_SHORT).show();
        try
        {
            SendWXAPI.dispatchResult(resp.errCode);
//            ShareManager.mCode = ((SendAuth.Resp)resp).code;
        }
        catch(Exception exception)
        {

        }
        finish();
    }
}
複製代碼

SendWXAPI:

public class SendWXAPI {
	public interface WXCallListener{
		void onCallFinish(int result);
	}
	
	private static ArrayList<WXCallListener> sWXCallListeners = new ArrayList<WXCallListener>();
	
	public static void dispatchResult(final int result)
	{
		synchronized(sWXCallListeners)
		{
			if(sWXCallListeners.size() > 0)
			{
				Handler handler = new Handler(Looper.getMainLooper());
				for(WXCallListener l : sWXCallListeners)
				{
					if(l != null)
					{
						final WXCallListener listener = l;
						handler.post(new Runnable()
						{
							@Override
							public void run() {
								listener.onCallFinish(result);
							}
						});
					}
				}
			}
		}
	}
	
	public static void addListener(WXCallListener l)
	{
		synchronized(sWXCallListeners)
		{
			if(sWXCallListeners.contains(l) == false)
			{
				sWXCallListeners.add(l);
			}
		}
	}
	
	public static void removeAllListener()
	{
		synchronized(sWXCallListeners)
		{
			sWXCallListeners.clear();
		}
	}
	
	public static void removeListener(WXCallListener l)
	{
		synchronized(sWXCallListeners)
		{
			if(sWXCallListeners.size() > 0)
			{
				for(int i = 0; i < sWXCallListeners.size(); i++)
				{
					if(l == sWXCallListeners.get(i))
					{
						sWXCallListeners.remove(i);
						i--;
					}
				}
			}
		}
	}
}
複製代碼

Constant:

public class Constant {
    public static final String APPID_WXPAY = "your weixin id";
    public final static String APPKEY_QZONE ="qzone key";
    public final static String APPKEY_SINA = "sinaid";
    public final static String REDIRECTURL_SINA = "sina redi";
}
複製代碼

MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Tencent mTencent = null;
    private IWeiboShareAPI mWeiboShareAPI;//微博
    private boolean isInstalledWeibo;
    private AuthInfo mAuthInfo;
    private String sAccess_token;
    private boolean sinaregister;
    private SsoHandler mSsoHandler;
    private int supportApiLevel;
    private static String Weibodec[] = {"", "biaoti", "biaoti", ""};
    private Bitmap bitmap = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        this.findViewById(R.id.share_qq).setOnClickListener(this);
        this.findViewById(R.id.share_qqzone).setOnClickListener(this);
        this.findViewById(R.id.share_weibo).setOnClickListener(this);
        this.findViewById(R.id.share_weixin).setOnClickListener(this);
        this.findViewById(R.id.share_circle).setOnClickListener(this);
        this.findViewById(R.id.login_qq).setOnClickListener(this);
        this.findViewById(R.id.login_weibo).setOnClickListener(this);
        this.findViewById(R.id.login_weixin).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.share_qq:
                if (!isQQAppInstalled(MainActivity.this)) {
                    return;
                }
                shareMsgToQQ(MainActivity.this);
                break;
            case R.id.share_qqzone:
                if (!isQQAppInstalled(MainActivity.this)) {
                    return;
                }
                shareToQZone(MainActivity.this, "內容", "標題", "https://www.baidu.com/img/bd_logo1.png", "https://www.baidu.com/");
                break;
            case R.id.share_weibo:
                if (!isInstallWeiBo(MainActivity.this)){
                    Toast.makeText(MainActivity.this,"沒有安裝微博",Toast.LENGTH_SHORT).show();
                    return;
                }
                sharetosinabySSO(MainActivity.this, "content", "http://blog.csdn.net/yuanzeyao/article/details/38781957", 1, bitmap);
                break;
            case R.id.share_weixin:
                if (!isWEIXINAppInstalled(MainActivity.this)){
                    Toast.makeText(MainActivity.this,"沒有安裝微信",Toast.LENGTH_SHORT).show();
                    return;
                }
                shareImgToWx(MainActivity.this,bitmap, "https://www.baidu.com/img/bd_logo1.png", true);
                break;
            case R.id.share_circle:
                if (!isWEIXINAppInstalled(MainActivity.this)){
                    Toast.makeText(MainActivity.this,"沒有安裝微信",Toast.LENGTH_SHORT).show();
                    return;
                }
                shareImgToWx(MainActivity.this,bitmap, "https://www.baidu.com/img/bd_logo1.png", false);
                break;
            case R.id.login_qq:
                break;
            case R.id.login_weibo:
                break;
            case R.id.login_weixin:
                break;
            default:
                break;
        }
    }


    /**
     * 是否安裝qq
     *
     * @param context
     * @return
     */
    public boolean isQQAppInstalled(final Context context) {
        try {
            //避免多線程同時調用,致使package manager has died at android.app.ApplicationPackageManager.getPackageInfo
            synchronized (MainActivity.class) {
                PackageInfo pInfo;
                pInfo = context.getPackageManager().getPackageInfo("com.tencent.mobileqq", PackageManager.GET_SERVICES);
                return pInfo == null ? false : true;
            }
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * qq分享
     * 消息
     *
     * @param content
     */
    public void shareMsgToQQ(Context content) {
        Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "標題");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "要分享的摘要");
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "https://github.com/tianzhijiexian/ShareLoginLib");
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "https://www.baidu.com/img/bd_logo1.png");
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "應用名稱");
        params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "其它附加功能");

        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constant.APPKEY_QZONE, content);
        }
        mTencent.shareToQQ((Activity) content, params, mIUiListener);
    }

    /**
     * qq分享
     * 圖片
     *
     * @param context
     */
    public void shareImgToQQ(Context context, String imageUrl) {
        Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imageUrl);

        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constant.APPKEY_QZONE, context);
        }

        mTencent.shareToQQ((Activity) context, params, mIUiListener);
    }

    private IUiListener mIUiListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {

        }

        @Override
        public void onError(UiError uiError) {
            String tag = uiError.errorMessage;
        }

        @Override
        public void onCancel() {

        }
    };


    //------------------------------------------qq空間--------------------------------------------------

    /**
     * @param content  分享內容(必填)
     * @param title    標題(必填)
     * @param imageUrl 圖片地址(必填)
     * @param linkUrl  點擊該條分享後的連接地址(必填)
     * @return
     */
    public void shareToQZone(Context context, String content, String title, String imageUrl, String linkUrl) {
        Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, linkUrl);

        //支持傳多個imageUrl,但目前只對第一個有效,暫不能多圖發送
        ArrayList<String> imageUrls = new ArrayList<String>();
        imageUrls.add(imageUrl);
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);

        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constant.APPKEY_QZONE, context);
        }
        mTencent.shareToQzone((Activity) context, params, mIUiListener);
    }

    //--------------------------------微博-------------------------------------

    /**
     * 是否安裝微博客戶端
     *
     * @param context
     * @return
     */
    public boolean isInstallWeiBo(Context context) {
        if (mWeiboShareAPI == null) {
            mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(context, Constant.APPKEY_SINA);
        }
        isInstalledWeibo = mWeiboShareAPI.isWeiboAppInstalled();
        return isInstalledWeibo;
    }

    /**
     *
     * @param context
     * @param content
     * @param path
     * @param type
     * @param thump
     */
    public void sharetosinabySSO(Context context, String content, String path, int type, Bitmap thump) {
        //sso受權
        mAuthInfo = new AuthInfo(context, Constant.APPKEY_SINA, Constant.REDIRECTURL_SINA, null);
        mSsoHandler = new SsoHandler((Activity) context, mAuthInfo);

        if (mWeiboShareAPI == null) {
            mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(context, Constant.APPKEY_SINA);
        }
        isInstalledWeibo = mWeiboShareAPI.isWeiboAppInstalled();
        supportApiLevel = mWeiboShareAPI.getWeiboAppSupportAPI();
        if (sAccess_token == null || sAccess_token.length() <= 0) {
            sinaregister = mWeiboShareAPI.registerApp();//將應用註冊到微博客戶端
            mSsoHandler.authorizeClientSso(new MyAuthListener(context,content, path, type, thump));
        } else {
            shareToWeiBo(context, content, path, type, thump);
        }

    }


    /**
     * 受權回調
     */
    private class MyAuthListener implements WeiboAuthListener {
        private String content;
        private String path;
        private int type;
        private Bitmap thump;
        private Context context;


        MyAuthListener(Context context,String c, String p, int t, Bitmap b) {
            content = c;
            path = p;
            type = t;
            thump = b;
        }

        @Override
        public void onComplete(Bundle values) {
            Oauth2AccessToken mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            sAccess_token = mAccessToken.getToken();
            // 判斷AccessToken是否有效
            if (mAccessToken.isSessionValid()) {
                shareToWeiBo(context,content, path, type, thump);
            } else {
                System.out.println("認證失敗");
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {

        }

        @Override
        public void onCancel() {

        }
    }


    /**
     * 分享到微博
     * @param context
     * @param content
     * @param path
     * @param type
     * @param thump
     */
    private void shareToWeiBo(Context context, String content, String path, int type, Bitmap thump) {
        if (isInstalledWeibo) {
            if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
                if (supportApiLevel >= 10351) {
                    // 1. 初始化微博的分享消息
                    WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                    //這裏指實現了分享文本內容 還能夠分享 圖片 視頻 音樂 聲音 網頁
                    if (path != null && path.length() > 0) {
                        ImageObject imageObject = new ImageObject();
                        imageObject.imagePath = path;//連接
                        weiboMessage.imageObject = imageObject;
                    }
                    if (content != null && content.length() > 0 && type > 0) {
                        TextObject textObject = new TextObject();
                        textObject.text = "#連接#";
                        weiboMessage.textObject = textObject;
                        WebpageObject mediaObject = new WebpageObject();
                        mediaObject.identify = Utility.generateGUID();
                        mediaObject.title = "這是標題";
                        //描述
                        mediaObject.description = Weibodec[type].toString().substring(0, Weibodec[type].length() > 81 ? 81 : Weibodec[type].length());
                        if (thump != null) {
                            mediaObject.setThumbImage(thump);
                        } else {
                            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
                            // 設置 Bitmap 類型的圖片到視頻對象裏
                            // 設置縮略圖。 注意:最終壓縮過的縮略圖大小不得超過 32kb。
                            mediaObject.setThumbImage(bitmap);
                        }
                        mediaObject.actionUrl = content;
                        weiboMessage.mediaObject = mediaObject;
                    } else if (type == 0) {
                        TextObject textObject = new TextObject();
                        textObject.text = "";
                        weiboMessage.textObject = textObject;
                    }
                    // 2. 初始化從第三方到微博的消息請求
                    SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
                    // 用transaction惟一標識一個請求,使用時間戳
                    request.transaction = String.valueOf(System.currentTimeMillis());
                    request.multiMessage = weiboMessage;
                    // 3. 發送請求消息到微博,喚起微博分享界面
                    if (mWeiboShareAPI.sendRequest((Activity) context, request)) {
                        System.out.println("success");
                    }
                }
            } else {
                Toast.makeText(context, "SDK不支持", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "沒有安裝新浪微博客戶端", Toast.LENGTH_LONG).show();
        }
    }

    //----------------------微信分享----------------------------------------------------

    /**
     * 是否安裝微信客戶端
     * @param context
     * @return
     */
    public boolean isWEIXINAppInstalled(Context context)
    {
        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.APPID_WXPAY);
        return api.isWXAppInstalled();
    }


    /**
     * 分享圖片到微信
     *
     * @param thumb          縮略圖
     * @param imgPath        圖片路徑
     * @param shareToSession true爲發送到微信好友,false爲發送到微信朋友圈
     * @return
     */
    public boolean shareImgToWx(Context context,Bitmap thumb, String imgPath, boolean shareToSession)
    {
        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.APPID_WXPAY);
        if(thumb == null || thumb.isRecycled())
        {
            Toast.makeText(context,"分享的縮略圖爲空",Toast.LENGTH_SHORT).show();
            return false;
        }

        if(!api.isWXAppInstalled())
        {
            Toast.makeText(context,"本機沒有安裝微信客戶端,沒法分享到微信",Toast.LENGTH_SHORT).show();
            return false;
        }

        if(imgPath == null || imgPath.length() <= 0)
        {
            Toast.makeText(context,"分享的圖片不能爲空",Toast.LENGTH_SHORT).show();
            return false;
        }

        if(api.isWXAppSupportAPI())
        {
            if(!shareToSession && api.getWXAppSupportAPI() < 0x21020001)
            {
                Toast.makeText(context,"所安裝的微信客戶端版本太低,不能分享到微信朋友圈",Toast.LENGTH_SHORT).show();
                return false;
            }

            WXImageObject imgObj = new WXImageObject();
            imgObj.setImagePath(imgPath);

            WXMediaMessage msg = new WXMediaMessage(imgObj);
            msg.mediaObject = imgObj;

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            thumb.compress(Bitmap.CompressFormat.JPEG, 100, output);
            byte[] result = output.toByteArray();
            try
            {
                output.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            msg.thumbData = result;

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "img" + System.currentTimeMillis();
            req.message = msg;
            //true爲發送到微信好友,false爲發送到微信朋友圈
            req.scene = shareToSession ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
            api.registerApp(Constant.APPID_WXPAY);
            if(api.sendReq(req))
            {
                SendWXAPI.addListener(mWXCallListener);//註冊回調
                return true;
            }
            else
            {
                Toast.makeText(context,"分享到微信失敗",Toast.LENGTH_SHORT).show();
            }
        }
        else
        {
            Toast.makeText(context,"所安裝的微信客戶端版本太低,沒法分享到微信",Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    /**
     * 回調
     */
    private SendWXAPI.WXCallListener mWXCallListener = new SendWXAPI.WXCallListener()
    {

        @Override
        public void onCallFinish(int result)
        {
            SendWXAPI.removeListener(mWXCallListener);
            if(result == BaseResp.ErrCode.ERR_OK)
            {
                Toast.makeText(MainActivity.this,"分享到微信成功",Toast.LENGTH_SHORT).show();
            }
        }

    };

    //---------------------------------------------------------------
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
            }
        }

    }


}
複製代碼

須要權限

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
複製代碼

myshare
相關文章
相關標籤/搜索