Unity3d Android SDK Access Resolution (iv) Generic Android SDK Access middleware

Source: Internet
Author: User

First, preface

Access to the Android SDK formally, in this time, in turn, access to Huawei, application Bao, Xiaomi, 360 and so on large and small 10 of the SDK, but also the unity Access Channel SDK has a more comprehensive understanding of the various channels of the pit is also a deep experience .... During the access process time is more tense, there is no way to make a summary of thought. Today is just free, then the code of the previous Access SDK was refactored, wrote a more general unity access to the Android SDK middleware, walnuts, posterity.

Go to the Chase

If there are some just questions about it, you can look at my previous three posts:

Portal:

Unity3d Android SDK Access parsing (a) Unity3d and Android calls to each other:
http://blog.csdn.net/yang8456211/article/details/51331358

Unity3d Android SDK Access Analysis (ii) Unity3d Android SDK design and two access methods
http://blog.csdn.net/yang8456211/article/details/51356193

Unity3d Android SDK Access parsing (iii) access to Android Library understanding (Ebeyun payment as an example)
http://blog.csdn.net/yang8456211/article/details/51435465

Ii. Some thoughts on middleware 2.1 Why not use a third-party platform
为什么要自己做一个Unity接入Android SDK的中间件呢?市面上例如Anysdk、易接这种第三方渠道是可以满足接入一次,生成大部分的SDK的,但是由于大渠道的审查越来越严格,已经禁止了这种第三方的平台SDK。因此,这些大渠道则必须由我们自己来接入了(不过二、三线渠道仍然是可以用第三方进行接入的),如果每个渠道都使用一个单独工程来管理,这无疑是一种非常浪费时间而且难以维护的事情,因此我想做的就是一个Unity的接入Android SDK的插件,所有的SDK的逻辑都封装好在Android层面,不同的游戏都可以按照相同的规则来接入进来,只需要调用通用的接口,准备好对应的资源即可。
2.2 How to do it conveniently

I want to make this middleware as versatile as possible, and it's easy to split and iterate. The logic for unity level is transparent, just focus on the timing of the interface call and the parameters passed in.

    • Universal, simple form

    • Focus only on SDK business logic

    • Call Simple

-- universal, simple form--

Let's talk about GM:

For unity Games, it is usually easier to access the SDK in the form of plugins, so from this point of view, I decided to make the jar package, not a library project, the jar package contains only pure code, no resources and no configuration files The caller can use it only by placing the jar package in the plugins/android/libs. For different games, there is no difference.

The final form is a uasdkinter jar package, where all the SDK logic is integrated into the jar.

The simple form also has a layer meaning that is convenient for integration and splitting:

Therefore, in the design of the package, each channel independent of a package channel code, theoretically, when we export the jar, the code of all channels directly into the jar package, because each code will be based on the incoming channel execution of a unique channel, the other code is placed there.

However, some channels will be code detection, such as 360, will be detected in the package contains millet payment related code, audit however, the corresponding we only need to hit the jar, tick off the corresponding packages can be. (because it is a refactoring code framework and does not contain many SDKs)

-- focus only on SDK business logic--

The middleware itself contains only design ideas and a concise framework. In the Access Channel SDK, we only need to put the SDK code of the channel into the middleware with certain rules.

So this middleware must be robust, after the framework is written, it is convenient to add new SDK code, no need to make big changes to the framework.

So I use the interface to achieve, each channel SDK has two classes, a management account information, a management payment information, account and payment separation.

Account Interface:

 Public InterfaceUagameinterf {//Initialize     Public void Init(Jsonobject Sjson);//Login     Public void Login(Jsonobject Sjson);//Log out     Public void Logout();//exit the game     Public void Exit();//Initialize parameter check     PublicBooleanInitParams(Jsonobject Sjson);//Set the life cycle function     Public void lifeCycle(intstatus);//Store user Information     Public void Upuserinfo(Jsonobject Sjson);}

Payment Interface:

publicinterface UAPayInterf {    // 支付    publicvoidpay();    // 初始化参数    publicinitParams(JSONObject sJson);}

When adding the SDK, only need to create a new account class and payment class, respectively, to implement the corresponding interface, instead of how to call the outer layer, the message is how to return unity, and only with the specific implementation of each interface can be, Do only focus on the business logic of the SDK (detailed description of the interface design).

-- Simple invocation--

On the call, C # initializes the Androidjavaclass object of the "package name + class name", using this object to invoke the corresponding function, which is different from creating a new activity inheritance unityplayeractivity pattern. This method avoids a series of egg-ache problems (e.g. middleware engineering needs to be the same as the package name of the game project)

Calls to C #:

The package name of the middleware project is: com.uainter.main
The interface class name is:uamain

Therefore, you can create Androidjavaclass objects in C #:

new AndroidJavaClass("com.uainter.main.UAMain");

In order to facilitate the invocation, the external interface has been made into a static method, so use callstatic to call, because each channel requires the parameter type and parameter number is not determined, because the incoming parameter is defined as a JSON.

For example, the Init method that calls the Xiaomi channel:
Xiaomi Channel needs 3 parameters: AppID, Appkey, Islandscape (login and pay horizontal screen or vertical screen display)

"{‘channel‘:‘11‘,‘debugmode‘:1,‘appid‘:‘xxx‘,‘appkey‘:‘xxx‘,‘islandscape‘:false}";ajc_SDKCall.CallStatic("uaInit",json);

Login method:

string"{}";ajc_SDKCall.CallStatic("uaLogin",json);

For each method that may have parameters passed in, set a JSON object as a parameter, such as the login method, when accessing the app Bao, you need to pass in the JSON data in a platform to determine whether it is login or QQ.

There are several interfaces exposed by the middle key:

2.3 Thinking of some special operations and handling of the activity life cycle

Theory I want to do not need to modify the activation activity, so the activity life cycle of processing, placed in C # to control, Android provides interface public void lifeCycle(int status); in this interface processing channel SDK needs to do the life cycle operation.

For example, Huawei:
(Android code)

     Public void lifeCycle(intStatus) {if(getactivity () = =NULL) {DYBGSDKUTIL.E ("Init not initialized, life cycle operation not performed");return; }Switch(status) { CaseDybgsdkconstants.onstart: Break; CaseDybGSdkConstants.onResume:BuoyOpenSDK.getIntance (). Showsmallwindow (Getactivity ()); Break; CaseDybGSdkConstants.onPause:BuoyOpenSDK.getIntance (). Hidesmallwindow (Getactivity ()); Buoyopensdk.getintance (). Hidebigwindow (Getactivity ()); Break; CaseDybgsdkconstants.onstop: Break; CaseDybGSdkConstants.onDestroy:OpenHwID.releaseResouce (); Buoyopensdk.getintance (). Destroy (Getactivity ()); Break;default: Break; }    }

(C # Call)

    voidOnapplicationpause (BOOLIspause) {if(Ispause) {stringJSON ="{' Status ': ' 3 '}"; Ajc_sdkcall.callstatic ("Ualifecycle", JSON); }        }voidOnapplicationfocus (BOOLIsfocus) {if(Isfocus) {if(Ajc_sdkcall! =NULL){stringJSON ="{' Status ': ' 1 '}"; Ajc_sdkcall.callstatic ("Ualifecycle", JSON); JSON ="{' Status ': ' 2 '}"; Ajc_sdkcall.callstatic ("Ualifecycle", JSON); }        }    }voidOnapplicationquit () {stringJSON ="{' Status ': ' 5 '}"; Ajc_sdkcall.callstatic ("Ualifecycle", JSON); }

(the corresponding status and life cycle)

    //Android activity life cycle     Public Static Final intOnStart =1; Public Static Final intOnresume =2; Public Static Final intOnPause =3; Public Static Final intOnStop =4; Public Static Final intOnDestroy =5; Public Static Final intOnrestart =6;
How do you deal with the areas where activity is needed?

Only when access to the application Bao, encountered the need to access the activity of the two methods Onnewintent and Onactivityresult, need to accept QQ and callback, this situation I did not think of any good way, only to create an activity, Then implement this two method and modify the activity to activate the activity for androidmanifest inside.

What happens when you have to customize your application?

Similar to activity, this time we create a new application.

Most of the SDK methods need to be called in the UI thread

This has been said before, and here is just a list of not detailed:

For example, login:

 public  static  void  ualogin  ( String jsonstring) {try  {final  JSO            Nobject Sjson = new  jsonobject (jsonstring); final             Uagameinterf Uamanager = Getsdkobj (SChannel); Activity.runonuithread (new  Runnable () { @Ov Erride  public  void  run  () {uamanager.login (Sjson);        }            });        } catch  (jsonexception e) {e.printstacktrace (); }    }
How to send a message back to unity
    // 发送消息回Unity3d    publicstaticvoiddybCallback(JSONObject rjson) {        UnityPlayer.UnitySendMessage(UAMain.callBackobj, UAMain.callBackFun,                rjson.toString());    }

where Callbackobj and Callbackfun, respectively, correspond to the name and callback method of the object that receives the return value. (Here I am a constant to write dead, or you can dynamically modify these two values by passing in the corresponding key in init)

As you can see, the return is also a JSON, which includes a "callbacktype" key to determine which interface callback is the result, such as the Init callback:

            JSONObject jsonObj = new JSONObject();            "1";            jsonObj.put("callbackType""Init");            jsonObj.put("code", code);            UAMain.dybCallback(jsonObj);
Third, the middleware external interface description
    • Uainit
publicstaticvoiduaInit(String jsonString)

Mainly used for the initialization of each channel SDK, the incoming JSON string must contain, DebugMode and channel These two key,channel is used to distinguish which channel is currently called, DebugMode is used to differentiate between debug mode and formal mode (the General SDK will have two modes), here the DebugMode I also used as a switch to display the log. The remaining key will be passed in according to the different parameters required by the SDK.

    • Ualogin
publicstaticvoiduaLogin(String jsonString)

General SDK does not have to pass in the jsonstring, directly pass an empty JSON string "{}", when some SDK needs to add the switch account function in the login function is, I will pass a type to come in, to determine whether the operation is to log in or switch accounts.

    • Ualogout
publicstaticvoiduaLogout()

For account exit, this interface does not require parameters.

    • Uaexit
publicstaticvoiduaExit()

To exit the game, the General SDK will have a pop-up box to display some forums or related advertising information, and this interface does not require parameters.

    • Uaupuserinfo
publicstaticvoid uaUpUserInfo

A dot for information is to report information such as creating roles, role escalation, exit, and so on.

    • Ualifecycle
publicstaticvoid uaLifeCycle

The invocation for the life cycle function.

    • Uapay
publicstaticvoid uaPay

For payment.

Iv. Follow-up thinking
    • Originally written this framework, it took about 2 days, the subsequent access to some problems encountered, but also some modifications to the middleware, in general, to meet the majority of the most in the Market SDK access (at least I have not encountered access now). After the refactoring is more concise, deleted a lot of useless things.

    • However, the SDK, which needs to listen for functions such as onnewintent, can be handled (creating a new activity to process), but not very satisfied. Thinking about whether to make a middleware in activity form is better (rather than a Java class), and of course, there is a life cycle of processing, feeling that many things have the space to optimize.

    • Spent a whole day writing things, but also hope that the "crawler" in the forwarding, but also leave a link to the original text, because not only I want to share the knowledge I have to others, I also hope from others to the valuable advice, point out my mistakes and shortcomings, this is the purpose of my writing this article, as a programmer the most precious things, Thank you here.

Source Address:
Https://github.com/yang8456211/UASDKInter

Yeung Kwong (Atany) Original, reproduced please indicate bloggers and blog links, without the permission of the blogger, prohibit any commercial use.
Post Address: http://blog.csdn.net/yang8456211/article/details/52231305
Blog Address: http://blog.csdn.net/yang8456211
This article follows "Attribution-non-commercial use-consistent" authoring public agreement

Unity3d Android SDK Access Resolution (iv) Generic Android SDK Access middleware

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.