user2596390
user2596390

Reputation: 31

Nanohttpd and Android service

I try to catch in my android application an event sent with an http request. Tanks to nanohttpd, the following code is functioning correctly and I receive the Hello Word in response, but now, I don't know how to execute an action in my Android service each time an html request is received (make a simple Toast for example or anything else...). How to link the NanoHTTPD class with my service class ?

My code :

public class WebServer extends NanoHTTPD {

    /**
    * Constructs an HTTP server on given port.
    */
   public WebServer()throws IOException {
       super(8080);
   }


@Override
   public Response serve( String uri, Method method,
           Map<String, String> header, Map<String, String> parms,
           Map<String, String> files )
   {
       System.out.println( method + " '222" + uri + "' " );
       String msg = "<html><body><h1>Hello server</h1>\n";
       msg += "</body></html>\n";
       //Toast.makeText(this, "http message received", Toast.LENGTH_LONG).show();
       return new NanoHTTPD.Response(msg );
   }

}

Here is the according Android service :

package com.example.domomaster;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class WebService extends Service {
  private final static String TAG = "WebService";
  WebServer webServer;

  @Override
  public IBinder onBind(Intent intent) {
    Toast.makeText(this, "service bind", Toast.LENGTH_LONG).show();
    return null;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    //Toast.makeText(this, "service starting", Toast.LENGTH_LONG).show();
    try
    {
      webServer = new WebServer();
      webServer.start();
    }
    catch( IOException ioe )
    {
      System.err.println( "Couldn't start server:\n" + ioe );
      System.exit( -1 );
    }
    Toast.makeText(this, "service Listening on port 8080", Toast.LENGTH_LONG).show();
    System.out.println( "Listening on port 8080. Hit Enter to stop.\n" );
    try { System.in.read(); } catch( Throwable t ) {
      System.out.println("read error");
    };
    return super.onStartCommand(intent,flags,startId);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "service destroyed", Toast.LENGTH_LONG).show();
  }

}

Upvotes: 2

Views: 2361

Answers (1)

froyohuang
froyohuang

Reputation: 56

NanoHTTPD starts a thread running the server socket ,that means the public Response serve method is invoked from the thread,so the question here turns to a more abstract one : how do a thread send messages to the UI thread or a service. In your case, you can pass an Handler from WebService to the WebServer; or send a broadcast from WebServer and received by WebService

Upvotes: 0

Related Questions