Search code examples
androidandroid-service

Calling Javascript from service android


I want to connect my android app to WAMP server. I'm using javascript to do it. I have a activity where I load an HTML file. Internally, the HTML file will load that javascript.

I want the server continues to run even when the phone is locked.

Now, the server connection drops when the phone is locked.

Follows the code of my activity:

mWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new JavascriptInterface(this), "JSInterface");
mWebView.setWebContentsDebuggingEnabled(true);

mWebView.setWebViewClient(
    new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.d(TAG,"Page loading finished");
            
            String ip = "XXX.XXX.XXX.XXX";
            mWebView.loadUrl("javascript:configureServerIp('"+ ip + "')");
        }
    }
);

Follows my JS file:

function configureServerIp(ip) {
    console.log("ip=>"+ip)
    if(ip != null) {
        connection = new autobahn.Connection({url: 'ws://'+ip+':8080/ws', realm: 'realm1'});

        connection.onopen = function (session) {
            openSession = session;
            console.log("SESSION: " + session);
            session.subscribe('bms.device.msg',onevent)
            session.subscribe('bms.device.request.location',onLocationRequest)
            session.subscribe('bms.device.request.config',onConfigRequest)
            window.JSInterface.isConnected(true);
        };

        connection.onClose = function(reason, details) {
            openSession = null;
            window.JSInterface.isConnected(false);
        }

        connection.open();

    }
}

Is there any way, we can call javascript function from a service? If it is possible, will allow make the server running even when the app is not in foreground.


Solution

  • I created WebView object inside my service and I got my js function called successfully.

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        webView = new WebView(this);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
    
        webView.setWebContentsDebuggingEnabled(true);
        webView.setWebViewClient(
            new WebViewClient() {
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    
                    for(int i=0; i<10; i++) {
                        webView.loadUrl("javascript:sample()");
                    }
    
                }
            }
        );
        webView.loadUrl("file:///android_asset/html/index.html");
        return START_NOT_STICKY;
    }