teaches you to quickly and efficiently access the sdk--Channel SDK (which is the interface for implementing the abstraction layer)

Source: Internet
Author: User
Tags abstract constructor json require wrapper

Little Black finally has his own home: http://www.uustory.com/, Welcome to sit down.


Preface: A lot of people do game development, estimates are more or less to take the Channel SDK, what UC, when Le, 91, millet, 360 ... according to statistics the domestic market is currently less than 100 channels, but also includes some small channels without SDK. Each channel SDK access method, much is similar. However, it is these small different, and let the SDK access, creating endless variables. So, before accessing the SDK, if you have no experience, or have not been trapped by the SDK, then when you see this series of articles, you are lucky, you can avoid all this. If you've been in a hole before and you're still in the pit, now is your time to be free.


first, each of the previous index to make it easy for the pro to check:

Remember the small black-Unified SDK access framework (like prisms and ANYSDK)

Teach you fast and efficient access to sdk--general ideas and architecture

Teach you fast and efficient access to the design of SDK--SDK access abstraction Layer

Teach you fast and efficient access to the sdk--Game Access SDK (abstract framework only)


In the previous article we showed the game's call when it needed to access the SDK. It simply invokes the single wrapper class of each plug-in provided by the abstraction layer. In each case, the corresponding plug-in interface is referenced in the wrapper class. So the instantiation of this interface is done, on the previous one, we say that he is the configuration read from under the asssets. It is then instantiated according to the complete class name that is filled in the configuration. This implementation class is implemented at the time of access to each channel. So, let's take the UC channel as an example and connect it to our U8 SDK.


First, according to the documentation provided by UC, we know that there are two major functions that require access to login and pay. So, corresponding, in our case, we need two classes, a class implementation of the abstract SDK Iuser interface, an implementation of the abstract SDK Ipay interface. Well, here we look again at the place where the class needs to be noticed. In an abstract-level article, we look at the instantiation of each plug-in:

	Public Object initcomponent (int type) {
		Class localclass = null;
		
		try {
			
			if (!issupportcomponent (type)) {
				
				log.e ("U8sdk", "the config of the U8SDK is not a support plugin type:" +type); C5/>return null;
			}
			
			String name = Getcomponentname (type);
			
			Localclass = Class.forName (name);
			
		} catch (ClassNotFoundException e) {
			//TODO auto-generated catch block
			e.printstacktrace ();
			return null;
		}
		
		try {
			return Localclass.getdeclaredconstructor (New Class[]{activity.class}). newinstance (New object[]{ U8sdk.getinstance (). GetContext ()});
		catch (Exception e) {

			e.printstacktrace ();
		}
		return null;
	}

As we can see, we are instantiating the constructor that invokes the implementation class with an activity parameter. This requires us to define a constructor with the activity parameter when implementing the plug-in interface. Let's look at the UC landing implementation class and the payment implementation class.

Package com.u8.sdk;

Import Com.u8.sdk.IUser;
Import Com.u8.sdk.U8SDK;

Import android.app.Activity;

public class Ucuser implements Iuser {

	private Activity context;
	
	Public Ucuser (Activity context) {
		This.context = context;
		THIS.INITSDK ();
	}
	
	public void Initsdk () {
		ucsdk.getinstance (). INITSDK (This.context, U8sdk.getinstance (). Getsdkparams ());
	}
	
	@Override public
	void Login () {
		ucsdk.getinstance (). Login (This.context, U8sdk.getinstance (). Getsdkparams ());
	}

}

Pay:

Package com.u8.sdk;

Import Com.u8.sdk.IPay;
Import Com.u8.sdk.PayParams;

Import android.app.Activity;

public class Ucpay implements Ipay {

	private Activity context;
	
	Public Ucpay (Activity context) {
		This.context = context;
	}
	
	@Override public
	void Pay (Payparams data) {
		ucsdk.getinstance (). Pay (This.context, data);
	}

}

First we look at the login plugin implementation class above, we can see that it implements the login interface, and defines a constructor that takes activity as its parameter. In the login method, the invocation of the login interface is done by invoking the login of the Singleton class UCSDK. At the same time, notice that there is a initsdk method in the login implementation class, which is called when the instance is instantiated. This is because the UC SDK requires that the SDK be initialized when the game starts to run.

Similarly, the payment implementation class inside, implements the Pay method, is also by invoking the UCSDK Singleton to complete the payment interface the call.


So, as you can see, all the problems are now simplified. It is necessary to implement all the functions that the UC SDK needs to implement in this singleton class UCSDK. Let's look at the code inside the UCSDK:

Package com.u8.sdk;
Import org.json.JSONException;

Import Org.json.JSONObject;
Import Com.u8.sdk.ActivityCallbackAdapter;
Import Com.u8.sdk.LoginResult;
Import Com.u8.sdk.PayParams;
Import Com.u8.sdk.SDKConfigData;
Import Com.u8.sdk.U8Code;
Import Com.u8.sdk.U8SDK;

Import Com.u8.sdk.utils.SDKTools;
Import android.app.Activity;
Import Android.app.ProgressDialog;
Import Android.content.DialogInterface;
Import Android.util.Log;
Import Cn.uc.gamesdk.UCCallbackListener;
Import cn.uc.gamesdk.UCCallbackListenerNullException;
Import cn.uc.gamesdk.UCFloatButtonCreateException;
Import Cn.uc.gamesdk.UCGameSDK;
Import Cn.uc.gamesdk.UCGameSDKStatusCode;
Import Cn.uc.gamesdk.UCLogLevel;
Import Cn.uc.gamesdk.UCLoginFaceType;
Import cn.uc.gamesdk.UCOrientation;
Import Cn.uc.gamesdk.info.FeatureSwitch;
Import Cn.uc.gamesdk.info.GameParamInfo;
Import Cn.uc.gamesdk.info.OrderInfo;

Import Cn.uc.gamesdk.info.PaymentInfo; public class Ucsdk {enum sdkstate{statedefault, stateiniting, StateiniteD, Statelogin, statelogined} private sdkstate state = Sdkstate.statedefault;
	Private Boolean loginafterinit = false;	
	
	Private ProgressDialog loadingactivity = null;
	
	private static UCSDK instance;
	
	Private Ucloglevel logLevel = Ucloglevel.debug;
	private int cpId;
	private int gameId;
	private int channel;
	
	
	Private Boolean debugmode = true;
		Private Ucsdk () {} public static UCSDK getinstance () {if (instance = = null) {instance = new Ucsdk ();
	} return instance;
		} private void Parsesdkparams (Sdkconfigdata params) {This.gameid = Params.getint ("Ucgameid");
		This.cpid = Params.getint ("Uccpid");
		This.channel = U8sdk.getinstance (). Getcurrchannel ();
		if (this.channel <= 0) {This.channel = Params.getint ("Ucchannel");
	} This.debugmode = Params.getboolean ("Ucdebugmode");
		} public void Initsdk (Activity context, Sdkconfigdata params) {this.parsesdkparams (params);
	THIS.INITSDK (context); } public void Login (Activity context, SDKconfigdata params) {this.parsesdkparams (params);
	This.login (context); }/** * must connect function <br> * SDK initialization function <br> */public void Initsdk (final Activity context) {this.state = SDK

		state.stateiniting;
			try {showwaitdialog (context); U8sdk.getinstance (). Setactivitycallback (New Activitycallbackadapter () {@Override public void onbackpressed ()
				{ucsdkexit (context);
				} @Override public void OnDestroy () {Ucsdkdestoryfloatbutton (context);			
			
			}		
				
			});
			if (loginafterinit) {//showprogressdialog (context);
			} gameparaminfo GPI = new Gameparaminfo ();//The values below are for reference only gpi.setcpid (THIS.CPID);
			Gpi.setgameid (This.gameid); Gpi.setserverid (0); 
			The server ID can be set according to the game itself, or incoming 0//In the nine tour community settings display Query recharge history and display switch Account button,//In the case of not set, by default, the production environment display query recharge History button, do not display the switch Account button//test Environment settings invalid

			Gpi.setfeatureswitch (New Featureswitch (True, false)); Set the SDK login screen for horizontal screen, personal center and Recharge page default to force vertical screen, cannot modify//UCGAMESDK.DEFAULTSDK (). SetOrientation (UCORientation.

			LANDSCAPE);

			Set the SDK login interface to portrait screen UCGAMESDK.DEFAULTSDK (). SetOrientation (Ucorientation.landscape); Set Login interface://use_widget-Simple Login interface//use_standard-Standard login Interface Ucgamesdk.defaultsdk (). Setloginuiswitch (ucloginfacety Pe.

			Use_widget);
			The Setuistyle is obsolete and does not need to be called.

			UCGAMESDK.DEFAULTSDK (). Setuistyle (Ucuistyle.standard); UCGAMESDK.DEFAULTSDK (). INITSDK (Context, This.loglevel, This.debugmode, GPI, new uccallbacklistener<string> () {@Override public void callback (int code, String msg) {LOG.E ("ucgamesdk", "UCGAMESDK initialization Interface returns data msg:
							
							"+ msg +", Code: "+ code +", Debug: "+ DebugMode +" \ n ");
							
							Hidewaitdialog (context); if (code = = ucgamesdkstatuscode.success) {if (state! = sdkstate.stateiniting) {u8sdk.getinstance (). Onresult (U8code.code_init_fail, "UC SDK INIT FAIL. Not initing.
									Curr State is: "+state);
								Return
				} state = sdkstate.stateinited;				U8sdk.getinstance (). Onresult (u8code.code_init_success, "UC SDK INIT SUCCESS");
								if (loginafterinit) {login (context);
								
								}}else{Hidewaitdialog (context);
								state = Sdkstate.statedefault;								
							U8sdk.getinstance (). Onresult (U8code.code_init_fail, "UC SDK INIT Fail.err:" +msg);
		}
						}
					});
		} catch (Uccallbacklistenernullexception e) {e.printstacktrace ();
		} catch (Exception e) {e.printstacktrace ();
		
		}} Private Loginresult Encodeloginresult (string sid) {String channel = "" + Getchannel ();		
		String expansion = "";
		Jsonobject ext = new Jsonobject ();
			try {ext.put ("ext", "U8");
		Expansion = Ext.tostring ();
		} catch (Jsonexception e) {e.printstacktrace ();
	} return new Loginresult (SID, Channel, expansion); public void Login (final Activity context) {if (state.ordinal () < SDKState.StateInited.ordinal ()) {Loginaft
			Erinit = true; INITSDK (contEXT);
		Return } if (! Sdktools.isnetworkavailable (context)) {u8sdk.getinstance (). Onresult (U8code.code_no_network, "The NETWORK is
			Unavailable ");
		Return
			} try {state = Sdkstate.statelogin; UCGAMESDK.DEFAULTSDK (). Login (context, new uccallbacklistener<string> () {@Override public void callback (int code, String msg)
					{LOG.E ("ucgamesdk", "UCGAMESDK Login interface return Data: code=" + code + ", msg=" + msg); Login successful. The SID can be obtained at this time.
					and use the SID to play the game's login logic.
						The client cannot directly get ucid if (code = = ucgamesdkstatuscode.success) {state = sdkstate.statelogined;
						String sid = Ucgamesdk.defaultsdk (). GetSID ();
						
						U8sdk.getinstance (). Onresult (u8code.code_login_success, sid);
						Loginresult result = Encodeloginresult (SID);					
						U8sdk.getinstance (). Onloginresult (result);
						Execution of the hover button creation method Ucsdkcreatefloatbutton (context);
					Perform the hover button display method Ucsdkshowfloatbutton (context);
				}else{state = sdkstate.stateinited;		U8sdk.getinstance (). Onresult (U8code.code_login_fail, msg); }//Login failed.
					The logon call should be performed before the initialization succeeds.
					if (code = = Ucgamesdkstatuscode.no_init) {//does not initialize the login call, requires the game to call the SDK initialization method INITSDK (context); }//Login to exit.
					The callback is executed when the login interface exits.
		if (code = = ucgamesdkstatuscode.login_exit) {//Login interface is closed, the game needs to determine whether the login is successful in the appropriate Operation}});
		} catch (Uccallbacklistenernullexception e) {e.printstacktrace (); }} private Paymentinfo Decodepayparams (Payparams payparams) {log.i ("ucsdk", "The Payparams is" +payparams.tos
		
		Tring ()); Paymentinfo pInfo = new Paymentinfo (); Create payment object, used to pass the recharge information//Set up custom parameters, this parameter does not do any processing,//After the recharge is completed, the SDK server notifies the game server recharge results intact to the game server value, the field is the service side callback Callbackinfo field I F (!
		Sdktools.isnullorempty (Payparams.getextension ())) {Pinfo.setcustominfo (payparams.getextension ());
		}//non-required parameter, not set, this parameter is deprecated, the default is passed in 0.
		If you are unable to pay, please check the open platform to see if the corresponding environment has been configured for the payment callback address, such as no configuration, if any, but still cannot pay please contact UC Technical Interface person.

		Pinfo.setserverid (0); Pinfo.setroleid (Payparams.getroleid ()); Set the ID of the user's game role, this is a required parameter, please input real data pinfo.setrolename (Payparams.getrolename ()) according to actual business data; Set the user's game role name, this is a required parameter, please according to the actual business data into the real data Pinfo.setgrade ("" +payparams.getrolelevel ());
		Set the user's game role level, this is optional parameter//non-required parameter, set the game to receive the order result callback address after the payment completes, must be the URL form with the HTTP header.

		Pinfo.setnotifyurl ("http://192.168.1.1/notifypage.do");
		When a amount is passed in as the amount value to call the payment function, the SDK will display the top-up channel according to the amount available payment method//If you pass in 6 yuan, do not show the top-up card option, because there is no $6 prepaid card on the market, it is recommended to use the amount that can display the prepaid card method
	Pinfo.setamount (Payparams.getprice ());//Set up the recharge amount, this is the optional parameter return pInfo; public void Pay (Activity context, payparams data) {try {if (!isinited ()) {u8sdk.getinstance (). Onresult (U8
				Code.code_init_fail, "The SDK is not inited.");
			Return } if (! Sdktools.isnetworkavailable (context)) {u8sdk.getinstance (). Onresult (U8code.code_no_network, "The NETWORK is
				Unavailable ");
			Return
			
			} paymentinfo PInfo = decodepayparams (data);

			UCGAMESDK.DEFAULTSDK (). Pay (context, PInfo, new uccallbacklistener<orderinfo> () {			@Override public void callback (int code, OrderInfo OrderInfo) {if (code = = Ucgamesdkstatuscode.no_init) { Login calls without initialization require a game call to the SDK initialization method U8sdk.getinstance (). Onresult (U8code.code_init_fail, "The SDK is not inited
							"); } if (code = = ucgamesdkstatuscode.success) {//successfully recharge if (orderInfo! = null) {STR
									ing Ordereid = Orderinfo.getorderid ();//Get order number Float OrderAmount = Orderinfo.getorderamount ();//Get Order Amount
									int payway = Orderinfo.getpayway ();
									String paywayname = Orderinfo.getpaywayname ();
									
									System.out.print (Ordereid + "," + OrderAmount + "," + Payway + "," + Paywayname ");
									
								U8sdk.getinstance (). Onresult (u8code.code_pay_success, "UC pay SUCCESS.");
							}}else{u8sdk.getinstance (). Onresult (U8code.code_pay_fail, "UC pay failed.");
								} if (code = = ucgamesdkstatuscode.pay_user_exit) {//user exits the recharge screen. U8sdk.geTinstance (). Onresult (U8code.code_pay_fail, "The user is exit.");				
		}							
							
						}
					});
		} catch (Exception e) {e.printstacktrace (); }}/** * must connect function <br> * Hover button creation and display <br> * Hover button must be guaranteed after the SDK is initialized successfully and then created need to be called in the UI thread <br> */Private V  OID Ucsdkcreatefloatbutton (final Activity context) {u8sdk.getinstance (). Runonmainthread (New Runnable () {public void Run () {try {//Create a hover button.
					The hover button will hover over the Gameactivity page, and the hover menu will be expanded when clicked, and the menu contains the operation entry for some//SDK functions.
					After creation is complete, it is not automatically displayed and needs to be called Showfloatbutton (Activity,//Double, Double, Boolean) method for display or hide.
								UCGAMESDK.DEFAULTSDK (). Createfloatbutton (Context, new uccallbacklistener<string> () {@Override
											public void callback (int statuscode, String data) {log.d ("Selectserveractivity ' Floatbutton callback",
								"StatusCode = =" + StatusCode + "data = =" + data);

				}
							}); } catch (Uccallbacklistenernullexception e) {E. Printstacktrace ();
				} catch (Ucfloatbuttoncreateexception e) {//TODO auto-generated catch block E.printstacktrace ();
	}
			}
		}); }/** * must connect function <br> * Hover button display <br> * Hover button display need to be called in UI thread <br> */private void Ucsdkshowfloatbutton (f Inal Activity context) {u8sdk.getinstance (). Runonmainthread (New Runnable () {public void run () {//Display hover icon, game can be in a
				Some scenes choose to hide this icon to avoid affecting the game experience try {ucgamesdk.defaultsdk (). Showfloatbutton (context, +, +, true);
				} catch (Uccallbacklistenernullexception e) {//TODO auto-generated catch block E.printstacktrace ();
	}
			}
		}); }/** * must connect function <br> * Hover button Destroy <br> * Hover button destroy need to call in UI thread <br> */private void Ucsdkdestoryfloatbutton (Final Activity context) {u8sdk.getinstance (). Runonmainthread (New Runnable () {public void run () {//Suspension button Destroy function Ucgamesdk.defaultsdk ()
			. Destoryfloatbutton (context);
	}
		}); }/** * Required function <br> * The method must be called before the game exits to clean up the work. Suggest exiting in the gameThe call in the event must be executed before the game exits <br> * If the game exits without calling the method, an unknown error may occur, causing the program to crash <br>/private void Ucsdkexit (final Activity C Ontext) {ucgamesdk.defaultsdk (). EXITSDK (Context, new uccallbacklistener<string> () {@Override public void C  Allback (int code, String msg) {if (ucgamesdkstatuscode.sdk_exit_continue = = code) {//Add this to continue the game,} else if (Ucgamesdkstatuscode.sdk_exit = = code)
					{//Join the Exit Game Code Ucsdkdestoryfloatbutton (context) here;
				System.exit (0);
	}
			}
		});
	} public int Getchannel () {return this.channel;
	} public boolean isinited () {return this.state.ordinal () >= SDKState.StateInited.ordinal ();
	} public boolean islogined () {return this.state.ordinal () >= SDKState.StateLogined.ordinal ();
		} private void Showwaitdialog (Activity context) {if (loadingactivity! = null) {return;
        } loadingactivity = new ProgressDialog (context);
        Loadingactivity.setindeterminate (TRUE); Loadingactivity.Setcancelable (TRUE);
        Loadingactivity.setmessage ("Initializing, please later ..."); Loadingactivity.setoncancellistener (New Dialoginterface.oncancellistener () {@Override public void OnCancel (Dialogin
			Terface arg0) {state = Sdkstate.statedefault;		
        }
		});
	Loadingactivity.show ();
		} private void Hidewaitdialog (Activity context) {if (loadingactivity = = null) {return;
		} Loadingactivity.dismiss ();
	Loadingactivity = null;
 }	
}

This class seems a bit large. But it doesn't matter. We peeled our way slowly. First, enter from the invocation portal of our implementation class. The first is INITSDK. Let's see what INITSDK has done:

INITSDK first analyzes the parameters: look at the Initsdk method of Ucuser, we get the parameters required by the current SDK through the U8sdk.getinstance (). Getsdkparams () method. So what are these parameters? These parameters are the parameters that each SDK needs to pass in at run time. This is the information you apply to the channel before you access the Channel SDK (Appid,appkey). You may have questions here, and this information is supposed to be different from each channel. How can this be obtained through the abstraction layer? That's right, how the abstraction layer gets it. Thanks to the packaging tools we're going to talk about, we're going to do this with a clever design. Here you first know that all channels of access need to appid and other information, here are directly through the U8sdk.getinstance (). Getsdkparams () method to get it.

Immediately after that, we saw the initsdk inside the U8sdk Iactivitylistener interface. This is because the UC SDK needs to do the work in some of the activity's system events.

Next, you can see just follow the UC demo inside down to go. The key is to initialize the callback after the good, regardless of initialization success or failure, it is best to call the next U8sdk.getinstance (). The Onresult () method to throw a state message to the abstraction layer. So you in debug debugging, in the game layer implementation of the interface to add output or toast can be in time to see these status information, convenient debugging and error checking.


Then, we look at the login method, the login method is the same, directly call the UC provides the login method, the key is in the login callback, we in addition to call the Onresult method, if the login is successful, we also need to call U8sdk.getinstance (). The Onloginresult (Result) method. This is because the game layer will handle the successful callback in the Onloginresult, and the data returned by the SDK needs to be encapsulated into the Loginresult class.


Finally, let's look at the pay method, which is as simple as the pay method. Just a lot of parsing of the payment parameters. Before we talked about the implementation of the abstraction layer, we talked about the payment parameter payparams. All the information in this class is available in the game. However, each channel may need to be different. Therefore, the various channels here need to be based on the needs of the channel itself, according to the need to take. Here, for example, we take the Decodepayparams method from the Payparams to get the parameters that UC needs. Then, again, we call the Onresult method in the callback to prompt for state information.


For other methods, to what hide the hover icon, show the hover icon is UCSDK here to access on it. Need to be called in the corresponding place.


So, here we have the UC SDK even if the access is complete. After the answer, his directory structure is as follows:



Here you may see the project inside, there are sdk_confgi.xml and sdk_manifest.xml. Here, we'll leave a suspense. Back when we talked about packing tools. As you can see here, we did not mention the permissions information that the SDK needs to set up in androidmanifest.xml and some activity or service data. I do not know how to use it after the answer, how to test, how to maintain it. All of this, we'll say later.


This article was written by: Xiao Hei


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.