Create Web Server in Android
import fi.iki.elonen.NanoHTTPD;
public class MyHTTPServer extends NanoHTTPD {
public MyHTTPServer() {
super(8080);
}
@Override
public Response serve(IHTTPSession session) {
String msg = “
Hello from Android TV HTTP Server!
“;
return newFixedLengthResponse(Response.Status.OK, “text/html”, msg);
}
public static void main(String[] args) {
MyHTTPServer server = new MyHTTPServer();
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code starts a HTTP server on port 8080 and returns a simple HTML message when a client makes a request to the server.
Here’s a simple example to demonstrate this:
On the mobile device, send an HTTP POST request to the Android TV’s IP address (e.g. http://192.168.0.100:8080/) with the text to be displayed as the body of the request.
On the Android TV, the web server can receive the request and extract the text from the body.
The extracted text can then be displayed on the TV screen using an Android view such as TextView.
import fi.iki.elonen.NanoHTTPD;
public class MyHTTPServer extends NanoHTTPD {
public MyHTTPServer() {
super(8080);
}
@Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
if (Method.POST.equals(method)) {
try {
session.getInputStream();
Map
session.parseBody(files);
String text = files.get(“postData”);
// display the text on the TV screen
displayText(text);
String msg = “Text received: ” + text;
return newFixedLengthResponse(Response.Status.OK, “text/plain”, msg);
} catch (IOException | ResponseException e) {
e.printStackTrace();
}
}
return newFixedLengthResponse(Response.Status.BAD_REQUEST, “text/plain”, “Bad Request”);
}
private void displayText(String text) {
// code to display the text on the TV screen
}
public static void main(String[] args) {
MyHTTPServer server = new MyHTTPServer();
try {
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}