问题
My Task is as follows: using IBM MobileFirst create a Hybrid app and implement a JS calculator. show date retrieved from native java APIs to the web page.
My attempts:
- I followed Documentations here and implemented the whole Native code onCreate method
I found this answer"the first one" illustrating that i should use it on onInitWebFrameworkComplete,
- Solution provided didn't work
- I am working with MobileFirst version 7
- full sample code is provided
Suggestion: should i create the whole action bar in native code then merge it in the cross ui, is that available? I only need to send a petite string of date
回答1:
I am not clear on your attempts, so here is a quick demonstration how to click a button in HTML and trigger the Send Action API to get the current Date in Java and return it to JavaScript, and then display it.
index.html
<button onclick="getDateFromJava();">show current date from Java</button>
main.js
function wlCommonInit(){
WL.App.addActionReceiver ("returneDdateFromJava", returnedDateFromJava);
}
function getDateFromJava() {
WL.App.sendActionToNative("retrieveDate");
}
function returnedDateFromJava(received){
if (received.action === "returnedDateFromJava"){
alert (JSON.stringify(received));
}
}
main Java class file
- Find
onInitWebFrameworkComplete
Add an
ActionReceiver
after theelse
:import com.worklight.androidgap.api.WLActionReceiver; ... ... public void onInitWebFrameworkComplete(WLInitWebFrameworkResult result){ if (result.getStatusCode() == WLInitWebFrameworkResult.SUCCESS) { super.loadUrl(WL.getInstance().getMainHtmlFilePath()); } else { handleWebFrameworkInitFailure(result); } ActionReceiver ActionReceiver = new ActionReceiver(); WL.getInstance().addActionReceiver(ActionReceiver); }
ActionReceiver class
package com.getDateApp;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import com.worklight.androidgap.api.WL;
import com.worklight.androidgap.api.WLActionReceiver;
public class ActionReceiver implements WLActionReceiver{
public void onActionReceived(String action, JSONObject data){
if (action.equals("retrieveDate")){
Date date = new Date();
JSONObject returnedDate = new JSONObject();
try {
returnedDate.put("dateFromJava", date);
} catch (JSONException e) {
e.printStackTrace();
}
WL.getInstance().sendActionToJS("returnedDateFromJava", returnedDate);
}
}
}
来源:https://stackoverflow.com/questions/31331579/android-mobilefirst-sending-data-from-native-to-cross-page