I have the following method
private void valida_webView() {
lk="url-serv";
final WebView myBrowser;
myBrowser = (WebView)findViewById(R.id.webView);
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("url-server");
Msg = (EditText)findViewById(R.id.msg);
btnSendMsg = (Button)findViewById(R.id.sendmsg);
btnSendMsg.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String msgToSend = Msg.getText().toString();
myBrowser.loadUrl("javascript:callFromActivity(\"" + msgToSend + "\")");
}
});
}
In this method, what I want is to send only the letter 'x' to a server. Currently I have defined a text field and send what is inside the text field, all programmed in the event onClick
of the button, but what I want to do is automatically load the system makes me sending the letter 'x' to the server, removing the text field and the button. This method is called in onCreate
.
The javascript callFromActivity function is as follows:
<p id="mytext">texto por defecto</p>
<script language="javascript">
function callFromActivity(msg){
document.getElementById("mytext").innerHTML = msg;
if(msg != "x"){ document.getElementById("mytext").innerHTML = "no hay x";}
else
{
document.getElementById("mytext").innerHTML = "hay x";}
}
</script>
Mainly what I need is that when receiving the "x" another action is executed on the server. The sending of this data "x" has to be automatic when loading the application in android, the tests I do when creating a text field with a button work correctly for me, but I could not let the function send automatically and without intervention of the user said data.
Greetings.
Friends have already solved my problem, I leave the following codes.
private void valida_version() {
final WebView myBrowser;
myBrowser = (WebView)findViewById(R.id.webView);
myBrowser.setWebViewClient(new WebViewClient());
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myBrowser.getSettings().setDatabaseEnabled(true);
myBrowser.loadUrl("url-server.php");
myBrowser.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
String msgToSend = "x";
myBrowser.loadUrl("javascript:callFromActivity(\"" + msgToSend + "\")");
}
});
}
and this is the server-side code.
<div id="webv"></div>
<div id="box_update_app"></div>
<p id="mytext"></p>
<script type="text/javascript">
function callFromActivity(msg){
document.getElementById("mytext").innerHTML = 'Mensaje: '+msg;
if(msg != "x"){
document.getElementById("mytext").innerHTML = "no hay x";
}else{
document.getElementById("mytext").innerHTML = "hay x";
}
}
</script>
Thank you very much for your help and guidance.
Greetings.