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

鋸齒流沙發表於2017-12-13

分享,已經成為了一個app的標配了,因為分享到微信,微博和qq等社交平臺有機會可以為自己的app帶來大量的流量,提升app的知名度,這是一個快速而有效的增加app使用者量的途徑,所以分享對一個app來說,分享到微信,微博等社交平臺是何其重要。

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

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

使用極光社會分享到可以參考這篇文章android整合極光社會化分享攻略,如果你想使用友盟社會化分享工具可以參考這篇文章Android整合友盟社會化分享功能。這兩篇文章都詳細介紹和實現了社會化分享。這裡就不講解使用極光社會分享和友盟來實現分享了。

ShareUtil

簡介

ShareUtil是一個綜合性的分享及登入工具庫,支援微信分享,微博分享,QQ分享,QQ空間分享以及Android系統預設分享,支援微信登入,微博登入以及QQ登入並獲取使用者資訊。

使用

在app下的build.gradle新增依賴

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

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)、使用ShareUtil

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

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

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

1、SharePlatform.QQ分享到qq;

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

3、SharePlatform.WEIBO分享到微博;

4、SharePlatform.WX分享到微信;

5、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);

需要指定分享平臺型別:

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

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

3、ShareConstant.SHARE_CHANNEL_SINA_WEIBO分享到微博;

4、ShareConstant.SHARE_CHANNEL_WEIXIN_FRIEND分享到微信;

5、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,其他渠道不支援
     *
     * 分享大圖注意點
     * 1、setShareBigImg為ture
     * 2、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社交平臺。

新增依賴

1、在專案外層的build.gradle中新增JitPack倉庫

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

2、在用到的專案中新增依賴

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

3、初始化配置

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";
    }
}
複製程式碼

4、分享

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

指定分享型別SsoShareType.QQ_ZONE,並且設定分享監聽。

5、登入

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手動實現分享功能。

手動實現分享功能

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

2、將分享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)來實現分享到微博。

微信分享

1、微信分享需要在包名為專案包名.wxapi的包下新增WXEntryActivity。

myshare

2、註冊

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

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

myshare

4、分享到微信和朋友圈

分享到微信和朋友圈都是使用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

相關文章