A gateway is a bridge between a client and a server. The client uses the gateway to access background service interfaces.
By using a gateway, you can:
Encapsulates the communication between the client and the server by using a dynamic proxy.
If the server and the client define the same interface, the server can automatically generate code and export it to the client.
Unified exception handling for
RpcException
, pop-up dialog boxes, toast message boxes, etc.
Mobile gateways support two access methods: Native AAR access and Component-based (Portal&Bundle) access.
Prerequisites
If you use native AAR, you must add mPaaS to the project Add mPaaS to your project.
If you use component-based access, you must first complete the component-based access process General steps.
Add an SDK
Native AAR mode
Install the Mobile Gateway Service component in the project by using AAR. For more information, see Manage AAR components.
Component-based (Portal&Bundle)
Install the Mobile Gateway Service component on the Components page in the Portal and Bundle projects.
Initialize mPaaS
If you use Native AAR method, you must initialize mPaaS.
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// mPaaS initialization
MP.init(this);
}
}
For more details, see Initialize mPaaS.
Generate RPC code
After the app is connected to the background service in the Mobile Gateway console, log on to the mPaaS console. In the left-side navigation pane, choose Mobile Gateway Service > Manage APIs > Generate code to download the RPC code of the client. For more information, see Register an API.
The downloaded RPC code structure is as follows, including RPC configuration, request model, and response model.
Call RPC
The client initiates the PRC call. Sample code:
// Obtain the client instance.
RpcDemoClient client = MPRpc.getRpcProxy(RpcDemoClient.class);
// Specify the request.
GetIdGetReq req = new GetIdGetReq();
req.id = "123";
req.age = 14;
req.isMale = true;
// Initiate an RPC request.
try {
String response = client.getIdGet(req);
} catch (RpcException e) {
// Handle RPC request exceptions.
Log.i("RpcException", "code: " + e.getCode() + " msg: " + e.getMsg());
}
RPC call exceptions are thrown through the RpcException
. You can handle the error based on the RpcException
code
result code. For more information about error codes, see Gateway result codes.