vijay053
vijay053

Reputation: 872

How to call Angular 6 Typescript function from android app using WebView?

I am working on a project where UI is already developed in Angular. Our requirement is to load that UI into Android webview. Now our UI need some information from host android device, like list of BLE devices or wifi list. So i need to make a bridge between android native code to Angular Typescript code. Till now I am able to call Android code from typescript code by creating an interface in Typescript as follows:

export class WebAppInterface {
    showToast(toast: String): any;
}

Same I have implemented in Android as follows:

@JavascriptInterface
public void showToast(final String msg) {
    mFragment.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(mFragment.getContext(), msg, Toast.LENGTH_LONG).show();
        }
    });
}

I am able to call again javascript function as follows:

mWebView.evaluateJavascript("javascript:sampleFunction()", null);

I have declared above sampleFunction() into script tag of index.html and not in angular typescript.

My question is, how to call a function which is written in typescript like cordova plugins does. (PS: I cannot use cordova in my project). Can we pass callback from Angular typescript code to android and call that function some how? Till now what I have understand that I have to call a javascript function from Android native code and in that javascript code I have to call Typescript code. Is this correct approach? Can somebody please suggest what is the correct approach for this as I am new to Angular and javascript.

Upvotes: 4

Views: 2988

Answers (1)

Thomas
Thomas

Reputation: 12019

Don't get confused by TypeScript: At runtime the web application (Angular) will run completely as JavaScript. TypeScript is transpiled during the build phase to regular JavaScript code. So what you need to do to be able to call your (TypeScript/JavaScript) Angular code from Android is to make sure it is globally reachable. This can be achieved by using the window object and attaching your function there in your Angular code. For example

window['foo'] = function() ...

In order to get a better (testable) architecture I suggest that you don't directly reference the window object, but instead provide your own dependency injection provider that returns the reference. This could be a good refactoring once your approach works.

Upvotes: 6

Related Questions