- Key Concepts
- Understanding How to Integrate the mimik Client Library into Android Applications
Understanding How to Integrate the mimik Client Library into Android Applications
Objective
The objective of this document is to describe the key concepts that developers need to understand in order to integrate the mimik Client Library with an Android application and then use the library in their programming activities.
Intended Readers
The intended readers of this document are Android software developers and system integrators that will be using the mimik Client Library when programming an Android application.
What You Need to Know Before You Start
In order to get the full benefit of this document, the intended readers should be familiar with the following:
- The basics of the purpose and use of the the mimik edgeEngine Runtime
- The basics of using an Access Token to access and work with the edgeEngine Runtime
- The basics of programming Android applications using the Gradle Build Tool
What You Will Learn from This Document
After reading this document you will understand:
- The reason for using the mimik Client Library in your Android application
- How to include the mimik Client Library as a project dependency in an Android application using Gradle
- How the mimik Client Library is initialized for use in your Android application at runtime
- How to use the mimik Client Library in your code to start and stop the edgeEngine Runtime deployed on an application's host device
- How to use the mimik Client Library in your code to get and save a mimik Access Token in your application at runtime
- How use the mimik Client Library to get additional information about the edgeEngine Runtime
- The concepts behind using the mimik Client Library to run and access an edge microservice from within an Android application
Understanding the Purpose of the mimik Client Library
The purpose of the mimik Client Library is to provide a programmatic way to work with the edgeEngine Runtime to access information about the mobile device on which the application is running as well as mobile devices running within a cluster of mobile devices that are hosting the edgeEngine Runtime. Also, the mimik Client Library allows developers to use edge microservices that are running within a particular cluster.
The edgeEngine Runtime has the ability to transform a mobile device into an edge computing device. Edge computing is a distributed computing framework that allows independent devices such as cell phones, mobile tablets and other types of IoT devices to do computationally intensive work internally using their own computing resources. Then, when the computation is completed, the result is passed on to other devices or back to a central server. It's the difference between having a cell phone that has the capability to do facial recognition using its own computing power as opposed to having to send a photo back for facial recognition processing at a central location. The benefit is that more useful work can be done faster, in a more flexible manner, while incurring less burden on the network.
Using the mimik Client Library allows developers to create applications that work with the edgeEngine Runtime to take advantage of the power and flexibility inherent in the edge computing paradigm.
Integrating the mimik Client Library using Gradle
At a high level integrating the mimik Client Library for use in an Android project is a multi-phase process. These phases are:
- Integrating the mimik Client Library using the Gradle Build Tool
- Initializing the mimik Client Library
- Starting up the edgeEngine Runtime using the mimik Client Library
- Using the mimik Client Library in your Android application
The sections that follow will describe the various aspects of the phases described above that developers need to understand in order to work with the mimik Client Library for Android.
Adding the mimik Client Library for Android Dependency
The mimik Client Library for Android is a dependency that gets included as a Maven repository. The segments that follow show an example of the declarations that developers will include in their Android project. The project* and module-level build.gradle
files define the required Maven repository, and dependencies and configuration values for the library.
The project-level settings.gradle
file declares the repositories that will be used by the project. Line 4
specifies the location of the mimik Maven repository.
1: dependencyResolutionManagement {2: repositories {3: maven {4: url "https://s3-us-west-2.amazonaws.com/mimik-android-repo"5: }6: }7: }
The module-level build.gradle
file declares the dependency for the module on Line 7
, and defines configuration values for the mimik Client Library on Line 3
.
1: android {2: defaultConfig {3: manifestPlaceholders = ["appAuthRedirectScheme": ""] // Placeholder, for use with CustomTab authentication methods4: }5: }6: dependencies {7: implementation 'com.mimik.edgesdk-android-client:edgemobileclient-core:0.3.8.3'8: }
Enable Cleartext Communication
edgeEngine hosts APIs on the local network interface. To allow this type of communication on Android devices, add the following property to the application in the module AndroidManifest.xml
.
1: <manifest>2: <application3: android:usesCleartextTraffic="true">4: </application>5: </manifest>
Initializing the mimik Client Library
In order to get the mimik Client Library up and running in an Android project, a developer needs to initialize it. Initialization involves importing a reference to EdgeMobileClient
and then creating an instance variable using the constructor.
The code listed below shows an example of the code a developer writes to create an instance of the mimik Client Library. Notice the use of the EdgeMobileClient(Context context, EdgeConfig edgeConfig)
constructor at Line 2.
The default EdgeConfig()
constructor automatically selects default parameters. This will have the edgeEngine Runtime host URLs using port 8083, and use the default license required to work with the edgeEngine Runtime.
1: EdgeMobileClient edgeMobileClient =2: new EdgeMobileClient(getContext(), new EdgeConfig());
You now have an initialized mimik Client Library in your Android application.
Starting the edgeEngine Runtime
In order to do work using the mimik Client Library APIs, the initialized edgeEngine Runtime needs to be running. To start up the edgeEngine Runtime using the mimik Client Library, add the following code to your Android project.
1: if (edgeMobileClient.startEdge()) { // Start edgeEngine runtime2: // edgeEngine started successfully3: Log.d("edgeEngine", "Started successfully");4: } else {5: // error with edgeEngine startup6: Log.d("edgeEngine", "Failed to start");7: }
Authorizing Access to the edgeEngine Runtime
Most of mimik Client Library APIs require an Access Token in order to be operational. Developers use the mimik Client Library to create an Access Token. The Access Token is based on the Developer ID Token they generated when creating their account in the mimik Developer Portal. The following describes the process of generating and saving an Access Token using the mimik Client Library.
Getting the Developer ID Token from the mimik Developer Portal.
Generating the Access Token that's used to work with various API within the mimik Client Library requires that the develop have a Developer ID Token on hand. Developers get a Developer ID Token from the mimik Developer Portal as shown in the illustration below.
A Developer ID Token is generated from within the particular mimik project that's registered on the mimik Developer Portal.
Generating the Access Token
Once developers have a Developer ID Token in hand, they'll use it in code with the instance of the mimik Client Library in order to generate an Access Token.
The segment below shows code that a developer uses in an Android application to generate an Access Token.
1: String developerIdToken = <DEVELOPER_ID_TOKEN>;2: String clientId = <CLIENT_ID>;3: String authorizationRootUri = "https://devconsole-mid.mimik.com"; // This is the default authorization URI4:5: DeveloperTokenLoginConfig config = new DeveloperTokenLoginConfig();6: config.setClientId(clientId);7: config.setAuthorizationRootUri(authorizationRootUri);8: config.setDeveloperToken(developerIdToken);9: edgeMobileClient.loginWithDeveloperToken(this, config, new EdgeResponseHandler() {10: @Override11: public void onError(EdgeRequestError edgeRequestError) {12: Log.d("edgeEngine", "Failed to generate access token " + edgeRequestError.getErrorMessage());13: }14:15: @Override16: public void onResponse(EdgeRequestResponse edgeRequestResponse) {17: String accessToken = ((AuthResponse)edgeRequestResponse).getAccessToken();18: Log.d("edgeEngine", "Got access token " + accessToken);19: }20: });
WHERE:
<DEVELOPER_ID_TOKEN>
is the Developer ID Token the developer retrieved from the mimik Developer Portal<CLIENT_ID>
is the Client ID the developer retrieved from the mimik Developer Portal
Notice that the Access Token is the value of accessToken
as set at Line 17
in the code above.
Retrieving the Access Token
The mimik Client Library saves the registered access token automatically. The access token can be retrieved using the method getCombinedAccessTokens()
.
1: CombinedAuthResponse savedTokens = mEdgeClient.getCombinedAccessTokens();2: String storedAccessToken = savedTokens.getMimikTokens().getAccessToken();
Stopping down the edgeEngine Runtime using the mimik Client Library
To shut down the edgeEngine Runtime, developers add the following code to their Android project:
1: edgeMobileClient.stopEdge();2: Log.d("edgeEngine", "Stopped");
Please note that due to the nature of edgeEngine shutdown process design this call is intentionally synchronous, main thread blocking API.
Getting additional Information from the edgeEngine Runtime
The mimik Client Library provides a number of API methods that return information about the edgeEngine Runtime. The segment below show an examples of some of the information a developer can get using the mimik Client Library API.
1: EdgeInfoResponse response = edgeMobileClient.getInfo();2: Log.d("edgeEngine", "Node ID " + response.getNodeId());
Deploying an edge microservice
Developers can use the mimik Client Library to deploy an edge microservice that's encapsulated in a pre-existing .tar
file.
Sometimes the edge microservice .tar
file will be stored in a source code repository for immediate download. Other times that .tar
file will need to be built from scratch using the source code for the edge microservice. It all depends on the build and deployment policies of the given organization. To learn the details of building an edge microservice into a deployable edge Image .tar
file, read Understanding the Strategies for Deploying an edge Microservice here.
The segment below shows the code a developer can use to deploy a microservice that is encapsulated in the .tar
file fictitiously named microservice.tar
and stored as a raw resource in the module. Notice the use of the mimik Client Library API method, mimikClientLibrary.deployMicroservice()
at Line 6
.
1: String accessToken = <ACCESS_TOKEN>;2: InputStream microserviceResource = getResources().openRawResource(R.raw.microservice);3:4: // Create microservice deployment configuration, dependent5: // on microservice implementation6: MicroserviceDeploymentConfig config = new MicroserviceDeploymentConfig();7:8: // Set the name that will represent the microservice9: config.setName("microservice");10:11: // Set the InputStream of the edge microservice12: config.setResourceStream(microserviceResource);13:14: // Set the filename that by which the edge client will identify15: // the microservice internally. This filename is associated internally16: // with the resource stream initialized above17: config.setFilename("microservice.tar");18:19: // Declare the URI by which the application code will access20: // the microservice21: config.setApiRootUri(Uri.parse("/microservice/v1"));22:23: // Deploy edge microservice using the client library instance variable24: MicroserviceDeploymentStatus status =25: edgeMobileClient.deployEdgeMicroservice(accessToken, config);26: if (status.error != null) {27: // Display microservice deployment error28: Log.d("edgeEngine", "Failed to deploy microservice! " + status.error.getMessage());29: } else {30: // Store the microservice API root URI31: String microserviceRoot = status.response.getContainer().getApiRootUri().toString();32: // Display a message indicating a successful microservice deployment33: Log.d("edgeEngine", "Successfully deployed microservice!");34: }
WHERE:
<ACCESS_TOKEN>
is the Access Token the developer generated previously using the mimik Client Library
Notice that the microservice API root URI is stored as microserviceRoot
, set at Line 31
in the code above.
Uninstalling an edge microservice deployment
The segment below shows the code a developer can use to undeploy (uninstall) an edge microservice from the edgeEngine Runtime running on an Android device. Add the following code to your Android project.
1: String accessToken = <ACCESS_TOKEN>;2:3: MicroserviceDeploymentConfig config = new MicroserviceDeploymentConfig();4: // Declare the name of the microservice to be uninstalled5: config.setName("microservice");6: MicroserviceDeploymentStatus status =7: edgeMobileClient.removeEdgeMicroservice(accessToken, config);8: if (status.error != null) {9: // Display microservice uninstall error10: Log.d("edgeEngine", "Failed to uninstall microservice! " + status.error.getMessage());11: } else {12: // Display microservice uninstall success13: Log.d("edgeEngine", "Successfully uninstalled microservice!");14: }15: }
WHERE:
<ACCESS_TOKEN>
is the Access Token the developer generated previously using the mimik Client Library
NOTE: The edgeEngine Runtime needs to be up and running for these API calls to work. |
---|
Calling an edge microservice
Once an edge microservice is deployed with the Android application, a developer can work with it using the mimik Client Library.
The code segment below shows an example of how to access and use an edge microservice programmatically using the mimik Client Library. HTTP requests are performed using OkHttpClient.
1: String randomNumberRoot = <MICROSERVICE_ROOT_URI>;2: String microserviceApiEndpoint = <MICROSERVICE_API_ENDPOINT>;3:4: // Construct an API request for the edge microservice5: OkHttpClient client = new OkHttpClient();6: Request request = new Request.Builder()7: .url(String.format(8: "http://127.0.0.1:%d%s/" + microserviceApiEndpoint,9: // use the client to get the default localhost port10: edgeMobileClient.getEdgePort(),11: randomNumberRoot)) // root URI determined by microservice deployment12: .build();13: client.newCall(request).enqueue(new Callback() {14: @Override15: public void onFailure(16: @NotNull Call call,17: @NotNull IOException e) {18: // Display microservice request error19: e.printStackTrace();20: Log.d("edgeEngine", "Failed to communicate with microservice! " + e.getMessage());21: }22:23: @Override24: public void onResponse(25: @NotNull Call call,26: @NotNull final Response response) throws IOException {27: if (!response.isSuccessful()) {28: // Display microservice unknown error29: Log.d("edgeEngine", "Microservice returned unexpected code! " + response);30: });31: } else {32: // Display microservice response33: Log.d("edgeEngine", "Microservice returned " + response.body().string());34: }35: }36: });
WHERE
<MICROSERVICE_ROOT_URI>
is the microservice API root URI acquired previously<MICROSERVICE_API_ENDPOINT>
is microservice API endpoint defined by the microservice
Review
In this document you learned the following:
- The purpose of the mimik Client Library
- The operational concept behind integrating the mimik Client Library with Android application code using the Gradle Build Tool and enabling cleartext traffic
- The concepts and code behind programmatically initializing the mimik Client Library
- The concepts and code behind starting and stopping an instance of the edgeEngine Runtime using the mimik Client Library
- The concepts and code behind using an Access Token in code to work with the mimik Client Library
- The concepts and code needed to get additional runtime information using the mimik Client Library
- The concepts and code needed to deploy an edge microservice using the using the mimik Client Library
- The concepts and code needed to uninstall (undeploy) a microservice using the using the mimik Client Library
- The concepts and code needed to work with a deployed edge microservice using the mimik Client Library