游戏sdk接入教程:接入应用宝渠道SDK之一登录篇

官方文档及SDK的下载地址为:http://wiki.open.qq.com/wiki/YSDK%E4%B8%8B%E8%BD%BD

 

在接入之前,需先在应用宝后台创建游戏,获取一些接入参数。

 

客户端所需要参数包括:手Q的app_id、微信的app_id 。

 

准备工作做为,正式开始接入,首先把应用宝的YSDKLibrary引用库导入到我们的工作环境中去,然后用我们demo工程去引用那个工程。

我这边的接入环境是Eclipse









至于demo工程如何创建在上一篇的接入文档中有详细教程,请至:

http://www.cnblogs.com/laohaizei/p/6724250.html

 

首先我们打开我们demo工程的AndroidManifest.xml文件。


然后复制以下代码

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:resizeable="true"
        android:smallScreens="true" />

    <!-- TODO GAME SDK接入必须权限模块 START -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.RESTART_PACKAGES" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <!-- TODO GAME SDK Midas接入配置 设置屏幕兼容声明 START -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.RESTART_PACKAGES" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <application
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- TODO GAME SDK接入YSDK登陆接入配置 START -->
        <activity
            android:name="com.tencent.ysdk.module.realName.impl.RegisterRealNameActivity"
            android:configChanges="orientation|screenSize|keyboardHidden"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" >
        </activity>

        <!-- TODO GAME SDK接入YSDK登陆接入配置 END -->
        <!-- TODO GAME SDK QQ接入配置 START -->
        <activity
            android:name="com.tencent.tauth.AuthActivity"
            android:launchMode="singleTask"
            android:noHistory="true" >
            <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="tencent@qq_app_id@" />
                <!-- TODO GAME 这里为游戏QQ登录的配置,游戏需要修改为自己手Q的appid -->
            </intent-filter>
        </activity>
        <activity
            android:name="com.tencent.connect.common.AssistActivity"
            android:configChanges="orientation|screenSize|keyboardHidden"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <!-- TODO GAME SDK QQ接入配置 END -->


        <!-- TODO GAME SDK 微信接入配置 START -->
        <activity
            android:name="com.tencent.tmgp.yybtestsdk.wxapi.WXEntryActivity"
            android:configChanges="orientation|screenSize|keyboardHidden"
            android:excludeFromRecents="true"
            android:exported="true"
            android:label="WXEntryActivity"
            android:launchMode="singleTop"
            android:taskAffinity="@package@.diff"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" >

            <!-- TODO GAME 这里为游戏微信登录的配置,游戏需要修改为自己的包名加.diff -->
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:scheme="@wx_app_id@" />
                <!-- TODO GAME 这里为游戏微信登录的配置,游戏需要修改为自己的微信appid -->
            </intent-filter>
        </activity>
        <!-- TODO GAME SDK 微信接入配置 END -->


        <!-- TODO GAME SDK Midas接入配置 START -->
        <activity
            android:name="com.tencent.midas.proxyactivity.APMidasPayProxyActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:screenOrientation="sensorLandscape"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <activity
            android:name="com.tencent.midas.wx.APMidasWXPayActivity"
            android:exported="true"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <activity
            android:name="com.tencent.midas.qq.APMidasQQWalletActivity"
            android:configChanges="orientation|screenSize|keyboardHidden"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />

                <data android:scheme="qwallet100703379" />
                <!-- TODO GAME 这里为米大师的默认配置,游戏不要修改 -->
            </intent-filter>
        </activity>
        <activity
            android:name="com.tencent.midas.jsbridge.APWebJSBridgeActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:windowSoftInputMode="stateAlwaysHidden" />
        <!-- TODO GAME SDK Midas接入配置 END -->

    </application>

</manifest>

以上是需要添加在AndroidManifest.xml中的。(@xxx@部分请注意替换修改)

然后到我们demo工程的AndroidManifest.xml全选替换粘贴

这样AndroidManifest.xml修改好了。

 

做完以上步骤,接下来,我们开始接入SDK的接口。

首先打开我们的MainActivity.java

打开的MainActivity.java应该是这个样子的


然后把下面的代码复制进去,注意别把第一行的代码覆盖了。

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import com.tencent.ysdk.api.YSDKApi;
import com.tencent.ysdk.framework.common.eFlag;
import com.tencent.ysdk.framework.common.ePlatform;
import com.tencent.ysdk.module.user.PersonInfo;
import com.tencent.ysdk.module.user.UserListener;
import com.tencent.ysdk.module.user.UserLoginRet;
import com.tencent.ysdk.module.user.UserRelationRet;
import com.tencent.ysdk.module.user.WakeupRet;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

	private final static String TAG = "demo";

	public static String openId = "";
	public static String pf = "";
	public static String pfKey = "";
	public static String accessToken = "";
	public static String payToken = "";
	public Context context = this;
	public Activity activity = MainActivity.this;
	public boolean isLogin = true;
	int logintype = 0;// 1是qq登录,2是微信登录

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		YSDKApi.onCreate(activity);
		YSDKApi.setUserListener(ysdkUser);
		YSDKApi.handleIntent(activity.getIntent());
	}
	
	/*--------------------------------登录接口-----------------------------------------*/
	public void qqLogin(){
		YSDKApi.login(ePlatform.QQ);
	}
	
	public void wxLogin(){
		YSDKApi.login(ePlatform.WX);
	}
	
	public void logout(){
		YSDKApi.logout();
	}

	/*--------------------------------生命周期-----------------------------------------*/
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		YSDKApi.onDestroy(activity);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		YSDKApi.onPause(activity);
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		YSDKApi.onRestart(activity);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		YSDKApi.onResume(activity);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		YSDKApi.onStop(activity);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		YSDKApi.handleIntent(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		YSDKApi.onActivityResult(requestCode, resultCode,data);
	}

	/*--------------------------------监听回调-----------------------------------------*/
	UserListener ysdkUser = new UserListener() {

		@Override
		public void OnWakeupNotify(WakeupRet ret) {
			// TODO Auto-generated method stub
			Log.d(TAG, "called");
			Log.d(TAG, "flag:" + ret.flag);
			Log.d(TAG, "msg:" + ret.msg);
			Log.d(TAG, "platform:" + ret.platform);
			int platform = ret.platform;
			// TODO GAME 游戏需要在这里增加处理异账号的逻辑
			if (eFlag.Wakeup_YSDKLogining == ret.flag) {
				// 用拉起的账号登录,登录结果在OnLoginNotify()中回调
			} else if (ret.flag == eFlag.Wakeup_NeedUserSelectAccount) {
				// 异账号时,游戏需要弹出提示框让用户选择需要登录的账号
				Log.d(TAG, "diff account");
			} else if (ret.flag == eFlag.Wakeup_NeedUserLogin) {
				// 没有有效的票据,登出游戏让用户重新登录
				Log.d(TAG, "need login");
			} else {
				Log.d(TAG, "logout");
			}
		}

		@Override
		public void OnRelationNotify(UserRelationRet ret) {
			// TODO Auto-generated method stub
			String result = "";
			result = result + "flag:" + ret.flag + "\n";
			result = result + "msg:" + ret.msg + "\n";
			result = result + "platform:" + ret.platform + "\n";
			if (ret.persons != null && ret.persons.size() > 0) {
				PersonInfo personInfo = (PersonInfo) ret.persons.firstElement();
				StringBuilder builder = new StringBuilder();
				builder.append("UserInfoResponse json: \n");
				builder.append("nick_name: " + personInfo.nickName + "\n");
				builder.append("open_id: " + personInfo.openId + "\n");
				builder.append("userId: " + personInfo.userId + "\n");
				builder.append("gender: " + personInfo.gender + "\n");
				builder.append("picture_small: " + personInfo.pictureSmall
						+ "\n");
				builder.append("picture_middle: " + personInfo.pictureMiddle
						+ "\n");
				builder.append("picture_large: " + personInfo.pictureLarge
						+ "\n");
				builder.append("provice: " + personInfo.province + "\n");
				builder.append("city: " + personInfo.city + "\n");
				builder.append("country: " + personInfo.country + "\n");
				result = result + builder.toString();
			} else {
				result = result + "relationRet.persons is bad";
			}
			Log.d(TAG, "OnRelationNotify" + result);

			// 发送结果到结果展示界面
		}

		@Override
		public void OnLoginNotify(UserLoginRet ret) {
			// TODO Auto-generated method stub
			switch (ret.flag) {
			case eFlag.Succ:
				Log.e(TAG, "Login success:" + ret.toString());
				openId = ret.open_id;
				payToken = ret.getPayToken();
				pf = ret.pf;
				pfKey = ret.pf_key;
				accessToken = ret.getAccessToken();
				Log.i(TAG, "platform:" + ret.platform);
				logintype = ret.platform;
				// token和uid
				Log.d(TAG, "uid:" + openId + "token:" + accessToken);

				new NetHelper().execute();

				break;
			// 游戏逻辑,对登录失败情况分别进行处理
			case eFlag.QQ_UserCancel:
				Log.e(TAG, "用户取消授权,请重试");
				// showTips("用户取消授权,请重试",localContext);
				break;
			case eFlag.QQ_LoginFail:
				Log.e(TAG, "QQ登录失败,请重试");
				// showTips("QQ登录失败,请重试",localContext);
				break;
			case eFlag.QQ_NetworkErr:
				Log.e(TAG, "QQ登录失败,请重试");
				// showTips("QQ登录失败,请重试",localContext);
				break;
			case eFlag.QQ_NotInstall:
				Log.e(TAG, "手机未安装手Q,请安装后重试");
				// showTips("手机未安装手Q,请安装后重试", localContext);
				break;
			case eFlag.QQ_NotSupportApi:
				Log.e(TAG, "手机手Q版本太低,请升级后重试");
				// showTips("手机手Q版本太低,请升级后重试", localContext);
				break;
			case eFlag.WX_NotInstall:
				Log.e(TAG, "手机未安装微信,请安装后重试");
				// showTips("手机未安装微信,请安装后重试", localContext);
				break;
			case eFlag.WX_NotSupportApi:
				Log.e(TAG, "手机微信版本太低,请升级后重试");
				// showTips("手机微信版本太低,请升级后重试", localContext);
				break;
			case eFlag.WX_UserCancel:
				Log.e(TAG, "用户取消授权,请重试");
				// showTips("用户取消授权,请重试",localContext);
				break;
			case eFlag.WX_UserDeny:
				Log.e(TAG, "用户拒绝了授权,请重试");
				// showTips("用户拒绝了授权,请重试",localContext);
				break;
			case eFlag.WX_LoginFail:
				Log.e(TAG, "微信登录失败,请重试");
				// showTips("微信登录失败,请重试",localContext);
				break;
			case eFlag.Login_TokenInvalid:
				Log.e(TAG, "您尚未登录或者之前的登录已过期,请重试");
				// showTips("您尚未登录或者之前的登录已过期,请重试",localContext);
				break;
			case eFlag.Login_NotRegisterRealName:
				// 显示登录界面
				Log.e(TAG, "您的账号没有进行实名认证,请实名认证后重试");
				// showTips("您的账号没有进行实名认证,请实名认证后重试", localContext);
				break;
			default:
				// 显示登录界面
				break;
			}
		}
	};

	// 客户端收到登录成功回调(正常登录,票据刷新),发送SDK服务端刷新票据
	private class NetHelper extends AsyncTask<Integer, Void, Integer> {

		@Override
		protected Integer doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			try {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("openid", openId);
				map.put("openkey", accessToken);
				map.put("pf", pf);
				map.put("pfkey", pfKey);
				map.put("payToken", payToken);
				String beforeSignString = "openid=" + openId + "&openkey="
						+ accessToken + "&payToken=" + payToken + "&pf=" + pf
						+ "&pfkey=" + pfKey + "clientKey";
				Log.e(TAG, "login beforeSignString:" + beforeSignString);
				String sign = md5(beforeSignString);
				map.put("sign", sign);
				// 以下为把map post到服务端
				// refreshResult = HttpUtil._post(TypeSDKBonjour_Tencent
				// .Instance().platform.GetData("tokenUrl"), map);
				// Log.i(TAG, "tokenUrl reuslt:" + refreshResult);
			} catch (Exception e) {

				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}

	}

	public static String md5(String string) {

		byte[] hash;

		try {

			hash = MessageDigest.getInstance("MD5").digest(
					string.getBytes("UTF-8"));

		} catch (NoSuchAlgorithmException e) {

			throw new RuntimeException("Huh, MD5 should be supported?", e);

		} catch (UnsupportedEncodingException e) {

			throw new RuntimeException("Huh, UTF-8 should be supported?", e);

		}

		StringBuilder hex = new StringBuilder(hash.length * 2);

		for (byte b : hash) {

			if ((b & 0xFF) < 0x10)
				hex.append("0");

			hex.append(Integer.toHexString(b & 0xFF));

		}

		return hex.toString();

	}

}


至此我们就把所有应用宝上线所需的登录接口完成了,添加UI并添加相应事件调用相应接口后,就是一个最简单的demo了

 

 

如果想要了解具体的接口作用,和相应参数的说明,查看代码中的注释或查看官方文档


如果想了解更多,请联系我们或关注官网


了解更多:www.typesdk.com
问题解答:1771930259
联系邮箱:qianyuzhou@typesdk.com
项目地址:https://github.com/typesdk




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值