Teach you high-speed and efficient access to the Sdk--unity Unified Access Channel SDK (Android)

Source: Internet
Author: User

U8SDK's design was designed to support games developed by a variety of game engines, not just Android's native platform. At the moment more than half hand tour, are adopted with Unity3d and COCOS2DX development, then here, we first step to show you, with unity development game, how to through the U8SDK to complete the multi-channel SDK access.

Unity Research and development of the hand tour, only need to call U8SDK abstraction layer can be completed multiple channels SDK access. Instead of coupling the various channel SDKs in unity, the logic layer of the game layer is simple, and the SDK section is absolutely reusable. Below, let's look at the main tasks required to call U8SDK in unity: 1. Establish a androidproject, as the intermediate coordination Project2 of U8SDK and Unity platform communication, and define a consistent communication data type, we use JSON format 3, In unity, a unified set of SDK invocation interfaces is completed through C #. Called to the logical layer. At the same time, multiple platforms (ANDROID,IOS,PC, etc.) interface completely the same.

This article. We're going to finish the first and second steps. 1, create a new Androidproject, and set Islibrary to True. Use this project as a library project so that when you compile, a jar package is generated under the Bin folder. Instead of a APK2, set dependent project for the U8SDK2 Abstraction Layer project, the same time the Unity3d provided by the Android jar package, copied to the project's Libs folder under 3, and then build two classes, One for U8unitycontext, this class inherits Unityplayeractivity. It is also the start activity of the game.

4, there is a Iu8sdklistener implementation class, the main implementation of some of the SDK callback methods we first look at the implementation of these two classes. And then we'll explain some of the key things:

public class U8unitycontext extends unityplayeractivity{public final static String Callback_gameobject_name = "(u8sdk_ callback) "; The name of the Gameobject that receives the callback notification in//unity public final static String Callback_init =" ONINITSUC ";// The SDK initializes a successful callback method name and unity in consistent public final static String Callback_login = "ONLOGINSUC";//sdk Login Successful callback method name and consistent public in unity Final static string callback_switch_login = "Onswitchlogin";//sdk the callback method name of the switch account and consistent public final static string in unity Callback_logout = "Onlogout";//sdk Logout callback method name and unity in uniform public final static String Callback_pay = "ONPAYSUC";/ The SDK payment succeeded callback method name and unity in consistent @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Initsdk ();} U8SDK Initialize public void Initsdk () {u8sdk.getinstance (). Setsdklistener (New Unityu8sdklistener (this)); U8sdk.getinstance (). Init (this); U8sdk.getinstance (). OnCreate ();} Login interface public void login () {u8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void run () { U8user.getinstance (). Login ();}); Define your own login interface public void loGincustom (Final String customData) {u8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void run () { U8user.getinstance (). Login (CustomData);}}); Switch account interface public void Switchlogin () {u8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void run () { U8user.getinstance (). Switchlogin ();});} Display User Center interface public void Showaccountcenter () {u8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void Run () {u8user.getinstance (). Showaccountcenter ();}});} Logout public void Logout () {u8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void run () { U8user.getinstance (). Logout ();});} Commit Extended Data public void Submitextradata (String data) {final Userextradata extradata = parsegamedata (data); U8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void run () {u8user.getinstance (). Submitextradata (Extradata);}});} SDK exit interface public void exit () {u8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void run () { U8user.getinstance (). exit ();}); PayInterface public void Pay (String data) {final Payparams params = parsepayparams (data); U8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void run () {u8pay.getinstance (). Pay (params);});} Does the SDK support the exit Acknowledgement feature public boolean issupportexit () {return u8user.getinstance (). Issupport ("Exit");} Does the SDK Support User Center public boolean issupportaccountcenter () {return u8user.getinstance (). Issupport ("Showaccountcenter");} Does the SDK support logout public boolean issupportlogout () {return u8user.getinstance (). Issupport ("logout");} Send Message to Unity public void Sendcallback (string name, String jsonparams) {if (jsonparams = = null) {jsonparams = "";} Unityplayer.unitysendmessage (Callback_gameobject_name, NAME, jsonparams);} Private Userextradata Parsegamedata (String str) {userextradata data = new Userextradata (); try {jsonobject json = new Jsonob Ject (str);d Ata.setdatatype (Json.getint ("DataType"));d Ata.setroleid (json.getstring ("Roleid"));d Ata.setrolename ( Json.getstring ("RoleName"));d Ata.setrolelevel (json.getstring ("Rolelevel"));d Ata.setserverid(Json.getint ("ServerID"));d Ata.setservername (json.getstring ("ServerName"));d Ata.setmoneynum (Json.getint (" Moneynum "));} catch (Jsonexception e) {e.printstacktrace ();} return data;} Private Payparams Parsepayparams (String str) {payparams params = new Payparams (); Try{jsonobject json = new Jsonobject (str) ;p Arams.setproductid (json.getstring ("ProductId"));p Arams.setproductname (json.getstring ("ProductName")); Params.setproductdesc (json.getstring ("Productdesc"));p Arams.setprice (Json.getint ("price"));p arams.setratio (0) ;//The field is deprecated without Params.setbuynum (json.getint ("Buynum"));p Arams.setcoinnum (Json.getint ("Coinnum"));p Arams.setserverid (Json.getstring ("ServerID"));p Arams.setservername (json.getstring ("ServerName"));p Arams.setroleid ( Json.getstring ("Roleid"));p Arams.setrolename (json.getstring ("RoleName"));p Arams.setrolelevel (Json.getint (" Rolelevel "));p Arams.setpaynotifyurl (" ");//The field is deprecated without Params.setvip (json.getstring (" VIP "));p Arams.setorderid ( Json.getstring ("OrderID"));p arams.setextension (json.getstring ("extension"));} catch (Exception e) {e.printstacktrace ();} return params;} public void Onactivityresult (int requestcode, int resultcode, Intent data) {u8sdk.getinstance (). Onactivityresult ( Requestcode, ResultCode, data); Super.onactivityresult (Requestcode, ResultCode, data);} public void OnStart () {u8sdk.getinstance (). OnStart (); Super.onstart ();} public void OnPause () {u8sdk.getinstance (). OnPause (); Super.onpause ();} public void Onresume () {u8sdk.getinstance (). Onresume (); Super.onresume ();} public void Onnewintent (Intent newintent) {u8sdk.getinstance (). Onnewintent (newintent); Super.onnewintent (newintent) ;} public void OnStop () {u8sdk.getinstance (). OnStop (); Super.onstop ();} public void OnDestroy () {u8sdk.getinstance (). OnDestroy (); Super.ondestroy ();} public void Onrestart () {u8sdk.getinstance (). Onrestart (); Super.onrestart ();}}

public class Unityu8sdklistener implements Iu8sdklistener{private U8unitycontext Context;private Boolean Isswitchaccount = false;//is currently switching account public Unityu8sdklistener (U8unitycontext context) {This.context = context;} @Overridepublic void Onresult (final int code, String msg) {//TODO auto-generated Method Stubu8sdk.getinstance (). Runonmai Nthread (New Runnable () {@Overridepublic void run () {switch (code) {Case U8Code.CODE_INIT_SUCCESS:context.sendCallback ( U8unitycontext.callback_init, NULL); Break;case U8Code.CODE_INIT_FAIL:Toast.makeText (context, "SDK initialization failed", Toast.length_short). Show (); Break;case u8code.code_login_fail://There is no need to hint. The General SDK has the hint//toast.maketext (context, "SDK Login failed", Toast.length_short). Show (); Break;case U8code.code_pay_fail: Toast.maketext (Context, "Payment failure", Toast.length_short). Show (); Break;case U8Code.CODE_PAY_SUCCESS:Toast.makeText ( Context, "Payment is successful, the time to account may be slightly delayed", Toast.length_short). Show (); break;}});} This interface has been deprecated @overridepublic void oninitresult (initresult result) {//TODO auto-generated methodstub//This interface has been deprecated}//SDK login succeeded callback @overridepublic void Onloginresult (String data) {LOG.D ("u8sdk", "SDK login succeeded without processing, Process login success in Onauthresult, such as the following: "); LOG.D ("U8SDK", data); This.isswitchaccount = False;tip ("SDK login succeeded");} Switch accounts. Need to go back to the login screen and pop up the SDK login interface @overridepublic void Onswitchaccount () {Context.sendcallback (U8unitycontext.callback_switch_ LOGIN, null);} Switch the account number and sign in successfully. Here and Login callback Onloginresult the same @overridepublic void Onswitchaccount (String data) {LOG.D ("u8sdk", "SDK switch account and login successfully, do not have to do processing.") Process login success in Onauthresult, such as the following: "); LOG.D ("U8SDK", data), This.isswitchaccount = True;tip ("Switch account Success");} Log out, need to go back to login interface, and Popup SDK login interface @overridepublic void Onlogout () {context.sendcallback (u8unitycontext.callback_logout, NULL );} After the SDK login is successful. Go to U8server for login authentication @overridepublic void Onauthresult (Utoken authresult) {if (!authresult.issuc ()) {tip ("SDK Login authentication failed, Confirm that the U8server is configured "); return;} Jsonobject json = new Jsonobject (), Try{json.put ("Issuc", Authresult.issuc ()), Json.put ("Isswitchaccount", Isswitchaccount), if (Authresult.issuc ()) {json.put ("UserID", Authresult.getUserID ()); Json.put ("Sdkuserid", Authresult.getsdkuserid ()); Json.put ("username", authresult.getusername ()); Json.put ("Sdkusername", Authresult.getsdkusername ()), Json.put ("token", Authresult.gettoken ());}} catch (Exception e) {e.printstacktrace ();} Context.sendcallback (U8unitycontext.callback_login, json.tostring ());} For mobile games, do not need to implement this interface, because the online game payment is through the server callback notification plus virtual currency. This interface is mainly used for stand-alone games. As a single-machine payment result callback interface @overridepublic void Onpayresult (payresult result) {//todo}private void tip (Final String tip) { U8sdk.getinstance (). Runonmainthread (New Runnable () {@Overridepublic void run () {Toast.maketext (context, Tip, Toast.length_short). Show ();}});}}

In U8unitycontext, we define a series of interfaces. These interfaces are called in unity.

For example, Login,switchlogin,logout. The methods themselves, however, do a simple package for the method provided by the U8SDK abstraction layer. By, U8sdk.getinstance (). Runonmainthread () to have all of the interfaces complete in the UI main thread.

There are two parts to the initialization of U8SDK. The first part is the initialization of the U8SDK itself, including the reading and parsing of the parameters, which requires the android:name of the application interface in the Androidmanifest.xml to be set to "Com.u8.sdk.U8Application". Note that this must be set, otherwise u8sdk cannot be initialized. Assume that the game has its own certain business needs to be completed in application, can be completed by implementing the Iapplicationlistener interface provided by U8SDK. The second part needs to be completed in the activity's OnCreate (depending on the game, it is also possible to invoke the initialization interface in the appropriate place in unity), include, set the U8SDK callback listener, initialize the load plug-in, and invoke the OnCreate callback. The following three steps are performed: U8sdk. getinstance(). Setsdklistener ( NewUnityu8sdklistener ( This)); U8sdk. getinstance(). Init ( This); U8sdk. getinstance(). OnCreate (); Unityu8sdklistener is the implementation class for U8SDK's callback simplified interface. All SDK-related callbacks are completed through these interfaces.

ONLOGINRESULT:SDK Login Successful callback ONSWITCHACCOUNT:SDK switch account callback ONLOGOUT:SDK logout callback Onauthresult:u8server login authentication callback on Result: All SDK operation succeeded or failed status callback when we receive a partial callback, we need to notify unity before it is included. The interfaces we write, such as pay and submitextradata, are all of the parameters. Here's how to solve the data structure problems of communication in unity and Android. Although Unity and Android communication can also use complex structures, I recommend using a simple, unified data protocol. Here we choose JSON. Simple and efficient. Just to be sure. The key on both sides of the data will be consistent. Unity calls the Android interface, for example, pay and Submitextradata are passed through a JSON string, which is then parsed here.

For Android, it is also necessary to notify unity in the same way, using a JSON-formatted string and then passing Unityplayer. Unitysendmessage(Gameobject, MethodName, Jsonparams) interface to complete the communication. All right, over this, part of Android, it's over. Again, do not forget to configure Androidmanifest.xml Oh, here is attached androidmanifest.xml file:

<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "COM.U8.SDK" android:versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "21 "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_launcher "Android:la                Bel= "@string/app_name" android:theme= "@style/apptheme" android:name= "Com.u8.sdk.U8Application" >             <activity android:name= "Com.u8.sdk.U8UnityContext" android:label= "@string/app_name" android:screenorientation= "Landscape" android:launchmode= "Singletask" android:configchanges= "O Rientation|keyboardhidden|screensize "> <intent-filter> <action android:n            Ame= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filteR> </activity> </application></manifest> 

Next. We need to be in unity to complete the next work, to be able to see the visit here: Unity Hand Tour access Channel SDK (Unity article)


Teach you high-speed and efficient access to the Sdk--unity Unified Access Channel SDK (Android)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.