-
Notifications
You must be signed in to change notification settings - Fork 1
User Guide
WebApp Api is Android extended Webview Client are flexible, safe and easier request your Api and supports for using Cross-Origin Resource Sharing (CORS).
This sample WebApp app uses App Message integration for send and receive messages through broadcasts.
add files AppMessage.java and AppMessageReceiver.java to your project
add files WebApp.java and WebAppApi.java to your project
add files jquery-3.6.1.min.js, c.js to your project in the assets/ directory.
add files index.html, api.php to your PHP server. Note: in api.php replace https://webappapi-server.azurewebsites.net with you server
The primary class to use is AppMessage which you can just create
AppMessage appmessage = new AppMessage(this);
There is also a class AppMessageReceiver available that can be used to create a new receiver callback, this will be used to get called when you received a message on your broadcast.
private AppMessageReceiver.ReceiverCallback appMessageReceiverCallback = new AppMessageReceiver.ReceiverCallback() {
@Override
public void onReceiveMessage ( int param, String event, String data){
switch (event) {
case "my_request_event_name": {
//To do
// here is where you go receive your api url response data
break;
}
case "test": {
System.out.println("message test received successful");
break;
}
}
}
};
Create a new App Message Receiver, you can use the AppMessageReceiver.ReceiverCallback parameter being passed to the appMessageReceiverCallback method that you have created above.
AppMessageReceiver appMessageReceiver = new AppMessageReceiver(appMessageReceiverCallback);
Now register the receiver in the appMessage, to identify the registered receiver add a receiver name, you can use the class name of activity
appMessage.registerReceiver(MainActivity.className,appMessageReceiver);
NOTE: you are free to reuse the same object appMessage for register multiple AppMessageReceiver.ReceiverCallback on appMessage.registerReceiver.
You can do a test, calling sendTo()
appMessage.sendTo(MainActivity.className,0,"test","Hello");
Can also send message to another activity you just need do this replace MainActivity.className to receiverName you want. Example appMessage.sendTo(MainActivity2.className
The primary class to use is WebApp.
The following is an example shows how to create a new WebApp and configure WebViewAssetLoader in CORS compilance policy, please check if you have assets/ directory on your project. Set domain as same you go use in the url of your server that will be used to Load the WebApp.
WebView webview = new WebView(this);
WebApp webapp = new WebApp(webview, new WebViewAssetLoader.Builder()
.setDomain("webappapi-server.azurewebsites.net")
.addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this))
.build());
Add the index.html on your server, call webapp to load it by passing the server url. At the method onLoadFinish will called if your server url is successfull loaded. Else if got any problem to load server url the method onLoadError will been called.
webapp.load("https://webappapi-server.azurewebsites.net/index.html",new WebAppCallback() {
@Override
public void onLoadFinish(WebView view, String url) {
//load server_url finished
webapp.detachWebAppCallback();
try {
// To do
// here
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void onLoadError(WebView view, WebResourceRequest request, WebResourceErrorCompat error) {
//load server_url error
webapp.detachWebAppCallback();
}
});
When you execute something asynchronously, you can move on to another task before it finishes.
By default javascript async is set to true. In this example onRequestApi call webapp.runJavascript() and then they will go run as Asynchronous mode.
private WebAppApiRequest webAppApiRequest = new WebAppApiRequest(){
@Override
public void onRequestCanceled() {
Add_Loading_Text("request canceled");
Toast.makeText(MainActivity2.this,"Request Api has canceled.",Toast.LENGTH_LONG).show();
}
@Override
public void onRequestApi(String api_url, JSONObject options, JSONObject callback) {
String js = "request_url('" + api_url + "',$.parseJSON( '" + options + "' ) ,$.parseJSON( '" + callback + "' ))";
webapp.runJavaScript(js);
}
};
-
private WebAppApiResponse webAppApiResponse = new WebAppApiResponse(){ @Override public void onResponseApi(String receiverName, int param, String event, String data) { appmessage.sendTo(receiverName,param,event,data); } @Override public void onResponseApiConnectionError(String receiverName) { Add_Loading_Text("connection error"); } @Override public void onResponseApiScriptError() { Add_Loading_Text("script error"); } };
Set WebAppApi response handle
webapp.api.setWebAppApiResponse(webAppApiResponse);
Create new a WebAppApi Task Asynchronous
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).
prepare("api.php",
new JSONObject(WebApp.DEFAULT_REQUEST_API_OPTIONS),
new JSONObject() {{
put("receiverName",MainActivity2.className); //can also change the receiverName to MainActivity.className
put("param",0);
put("event","my_request_event_name");
}})
.execute();
When you execute something synchronously, you wait for it to finish before moving on to another task.
In this example onRequestApi call webapp.evalJavaScript() and then they will go run as synchronous mode. In this case to get full return we need configure async, see how configure it in next step.
private WebAppApiRequest webAppApiRequest = new WebAppApiRequest(){
@Override
public void onRequestCanceled() {
Add_Loading_Text("request canceled");
Toast.makeText(MainActivity3.this,"Request Api has canceled.",Toast.LENGTH_LONG).show();
}
@Override
public void onRequestApi(String api_url, JSONObject options, JSONObject callback) {
String js = "request_url('" + api_url + "',$.parseJSON( '" + options + "' ) ,$.parseJSON( '" + callback + "' ))";
webapp.evalJavaScript(js, new ValueCallback() {
@Override
public void onReceiveValue(Object value) {
//To do
// on request completed
}
});
}
};
Configure asyn to work in synchronously.
JSONObject joptions = new JSONObject(WebApp.DEFAULT_REQUEST_API_OPTIONS);
joptions.put("async",false);
Configuration of App Message to send the response to receiverName you want. in this example the response will go return to the App Message Receiver in Mainactivity3.
JSONObject jcallback = new JSONObject() {{
put("receiverName",MainActivity3.className);
put("param",0);
put("event","my_request_event_name");
}};
Set WebAppApi response handle
webapp.api.setWebAppApiResponse(webAppApiResponse);
Create new a WebAppApi Task Synchronous
webapp.api.newTask(new WebAppApiTask(webAppApiRequest))
.prepare("api.php?id=0", joptions,jcallback)
.execute();
Create On Demand Tasks
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=0", joptions,jcallback).execute();
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=1", joptions,jcallback).execute();
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=2", joptions,jcallback).execute();
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=3", joptions,jcallback).execute();
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=4", joptions,jcallback).execute();
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=5", joptions,jcallback).execute();
Create On Demand "Parallel" Tasks
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=0", joptions,jcallback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=1", joptions,jcallback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=2", joptions,jcallback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=3", joptions,jcallback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=4", joptions,jcallback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
webapp.api.newTask(new WebAppApiTask(webAppApiRequest)).prepare("api.php?id=5", joptions,jcallback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);