Calling an Android function from AngularJS controller - javascript

I have a problem which I need some help with. I'm trying to call an android function by using an angular controller in my frontend, but I can't get it to work.
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView)findViewById(R.id.activity_main_webview);
mWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new AngularJSInterface(this), "Android");
mWebView.loadUrl("http://192.168.70.101:3000/");
}
AngularJSInterface:
public class AngularJSInterface {
Context mContext;
AngularJSInterface(Context c) {
mContext = c;
}
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
Angular Controller:
angular.module('app').controller('ComplaintCtrl', function ($scope, $http, complaintService) {
$scope.showToast = function(toast) {
Android.showToast(toast);
console.log("toast");
}
});
The HTML:
<button label="toast" ng-click="showToast('Visar toast från angularJS')">toast</button>
Error from console:
ReferenceError: Android is not defined
at Scope.$scope.showToast (http://localhost:3000/scripts/controllers/addcomplaint.js:34:3)
at http://localhost:3000/bower_components/angular/angular.js:10567:21
at http://localhost:3000/bower_components/angular-touch/angular-touch.js:438:9
at Scope.$eval (http://localhost:3000/bower_components/angular/angular.js:12412:28)
at Scope.$apply (http://localhost:3000/bower_components/angular/angular.js:12510:23)
at HTMLButtonElement.<anonymous> (http://localhost:3000/bower_components/angular-touch/angular-touch.js:437:13)
at HTMLButtonElement.jQuery.event.dispatch (http://localhost:3000/bower_components/jquery/dist/jquery.js:4409:9)
at HTMLButtonElement.elemData.handle (http://localhost:3000/bower_components/jquery/dist/jquery.js:4095:28)
This is the first time I'm using this sort of thing and I'm not quite sure how to actually do it. I've tried looking for answers by googling but with no luck. What am I doing wrong?

Either change your toast function to static and call it directly or instantiate it first. And, you have no class named as Android instead you have created AngularJSInterface. Change you Android.showToast to AngularJSInterface.showToast (if using static).

Related

How to access a MP3 file bundled with an Android application from within a WebView?

I have put a MP3 file under assets folder in my Android application and tried to access it from within a WebView (HTML file) using this JS code:
var audio = new Audio('file:///android_asset/song.mp3')
audio.play()
But this does not work. Any idea how to do this?
This Should help.
WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview=(WebView)findViewById(R.id.webview);
webview.setWebViewClient(new MyWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/song.mp3");
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
playaudio();
return true;
}
}
private void playaudio(){
int i=R.raw.test;
Log.v("id of file",""+i);
if(i!=0){
MediaPlayer player = new MediaPlayer().create(getBaseContext(),i);;
player.setVolume(0.9f, 0.9f);
player.start();
}
}

Android webview - JavaScript callback not working?

I am using a WebView to display a web-page on an android application. https://developer.android.com/guide/webapps/webview.html
After clicking a button from the HTML, I can successfully get to the Android class WebAppInterface (From the example) and display a "Toast" alert, but trying to callback to the a javacsript function defined in my web-page is not working.
This is the code of the web-page: (Android.html)
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
if (typeof Android != 'undefined')
Android.showToast(toast);
}
function ChangeColor()
{
document.body.style.background = 'pink';
}
</script>
This is the code of the MainActivity of the Android app. It loads the url and displays it.
public class MainActivity extends AppCompatActivity {
WebView m_Webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_Webview = (WebView) findViewById(R.id.webview);
WebSettings webSettings = m_Webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
m_Webview.setWebViewClient(new WebViewClient());
m_Webview.loadUrl("android.html");
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this,webView), "Android");
}
}
This is the WebAppInterface on the Android app:
public class WebAppInterface {
Context mContext;
WebView mView;
/** Instantiate the interface and set the context */
WebAppInterface(Context c,WebView w) {
mContext = c;
mView = w;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
mView.loadUrl("javascript:ChangeColor()");
}
}
The JavaScript function ChangeColor is not getting called after the toast is getting displayed.
For more reference see: https://stackoverflow.com/a/14145116/7751339
Thanks!
The solution was to use the "post" function like this:
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
// WebView Web = new WebView(mContext);
// mView.getSettings().setUserAgentString("Android WebView");
mView.post(new Runnable() {
public void run() {
mView.loadUrl("javascript:ChangeColor()");
}
});
}
Also on KitKat and forward you need to use evaluateJavascript:
mView.evaluateJavascript("ChangeColor();",null);

Open activity from WebView-javascript function clicked - android studio

in MainActivity found my WebView i want show another activity when i click on button in javascript function
this code show another activiy when i click on botton1 but i want show when i click from javascrip
My MainActivity
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
});
}
}
My Html code
<button onClick="jsMethod();">Call Java Activity Method</button>
<script type="text/javascript">
function jsMethod(){
activity.TestMethod();
}
</script>
I ask the developers to help me

WebView can't call JavaScript function

I have tried everything and still doesn't work, please help:
I setup my WebView here:
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
private MyWebViewClient mWebViewClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
mWebViewClient = new MyWebViewClient(context);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.addJavascriptInterface(mWebViewClient, "Android");
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setDomStorageEnabled(true);
mWebView.setWebViewClient(mWebViewClient);
mWebView.loadUrl("file:///android_asset/index.html");
}
}
This is where I call my function from JS:
<script>
$("#logInButton").click(function(){
if(isAndroid){
Android.onJavaLogIn();
}
return false;
});
</script>
<input type="button" value="Log In" id="logInButton" />
Here is how I handle it:
public class MyWebViewClient extends android.webkit.WebViewClient {
private MainActivity context;
public MyWebViewClient(MainActivity context) {
this.context = context;
}
#JavascriptInterface
public void onJavaLogIn(){
context.onMainLogIn();
}
}
public class MainActivity extends ActionBarActivity {
public void onMainLogIn(){
mWebView.loadUrl("javascript:onJSLogIn();");
}
}
This is the JS function it's suppose to call:
<script>
function onJSLogIn(){
$("#logInButton").hide();
$("#logOutButton").show();
}
</script>
The entire chain seem to be correct, and I verify via debug that onMainLogIn() in MainActivity does get called, but the JS function onJSLogIn() never get called, why?
It turn out WebView only work on the main UI thread. So I had to warp the call function like this:
public void onMainLogIn(){
this.runOnUiThread(new Runnable() {
#Override
public void run() {
mWebView.loadUrl("javascript:onJSLogIn();");
}
});
}
Yes, here everything looks fine. Since we can't debug it, we can only suggest few things. 1. First write one alert in onJSLogIn JS method to make sure function not getting called.Because logInButton, logOutButton dom elements might not have loaded. 2. Connect your webview to remote debug and check for errors using chrome ADB tool.

image included javascript not appear in the webView

I used webView to show javaScript,one image was included in the javaScrip,but the webView not run the image on the contrary appear a "?"image. Idonot why?
my code:
demo.html
<html>
<script language="javascript">
/* This function is invoked by the activity */
function wave() {
document.getElementById("droid").src="android_waving.png";
alert("2");
}
</script>
<body>
<!-- Calls into the javascript interface for the activity -->
<a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
margin:0px auto;
padding:10px;
text-align:center;
border:2px solid #202020;" >
<img id="droid" src="android_normal.png"/><br>
Click me!
</div></a>
</body>
</html>
public class webJsDemo extends Activity {
/** Called when the activity is first created. */
private WebView mWebView;
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.wv1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
mWebView.setWebChromeClient(new MyWebChromeClient());
mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
mWebView.loadUrl("file:///android_asset/demo.html");
}
final class DemoJavaScriptInterface {
DemoJavaScriptInterface() {
}
/**
* This is not called on the UI thread. Post a runnable to invoke
* loadUrl on the UI thread.
*/
public void clickOnAndroid() {
mHandler.post(new Runnable() {
public void run() {
mWebView.loadUrl("javascript:wave()");
}
});
}
}
/**
* Provides a hook for calling "alert" from javascript. Useful for
* debugging your javascript.
*/
final class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
// TODO Auto-generated method stub
Log.d("aa", message);
Log.d("url", url);
Log.d("result", ""+result);
result.confirm();
return super.onJsAlert(view, url, message, result);
}
}
}
i put android_normal.png and android_waving.png in the assets and drawable folder
the result
Did you try putting your image in the same location your html file is?

Categories

Resources