Thursday 28 February 2019

View index.html found in the assets folder using NanoHttpd server embedded within my app

I have an app (Let's call it the Main App) which has an index.html page in the assets folder. The index.html is a simple HTML file with some JavaScript. It doesn't need PHP or MySql.

What I'm trying to do is embed the NanoHttpd server within my Main app, and automatically start the Nano server when the app starts or resumes, and view my index.html file within my app. While I know I can use the

webView.loadUrl("file:///android_asset/index.html"); 

to access the index.html file, it is impossible to do that for this scenario. Hence the need to use a webserver.

Right now I have a different dedicated app as a web server, which runs at http://localhost:8080. When I open the Main app, it works automatically. As you can see, in order to view the HTML file, you need to launch the web server, start it, then go back to the Main app and start it. I wanted a solution where the NanoHttpd server starts automatically when I lunch my Main App and starts showing the index.html contents on the webview. Here is my code which works perfectly using my Main App and a web server

   WebView wv;
   wv = (WebView) findViewById(R.id.webView1);
   WebSettings webSettings = wv.getSettings();
   webSettings.setJavaScriptEnabled(true);
   wv.loadUrl("http://localhost:8080/index.html");   

While O couldn't find the exact documentation for it, I tried two different approaches from the following links

  1. Using NanoHTTPD in Android

  2. http://programminglife.io/android-http-server-with-nanohttpd/

Both didn't work, One just shows a white page while the others just gives me a response that the server is running.

So how can I automatically start NanoHttpd server when my app starts and automatically launch an html file from my assets folder to a webview? If it's too much to ask for the NanoHttpd, is there another way to embed a webserver with an app and launch the index.html?



from View index.html found in the assets folder using NanoHttpd server embedded within my app

No comments:

Post a Comment