我尝试在我的Android应用程序中捕获一个带有http请求的事件。坦克到nanohttpd,下面的代码运行正常,我收到了Hello Word作为回应,但现在,我不知道如何在每次收到html请求时在我的Android服务中执行一个动作(制作一个简单的Toast例如或其他任何东西......)。如何将NanoHTTPD类与我的服务类链接?
我的代码:
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 );
}
}
以下是相应的Android服务:
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();
}
}
答案 0 :(得分:0)
NanoHTTPD启动一个运行服务器套接字的线程,这意味着从线程调用公共Response服务方法,因此这里的问题变成了一个更抽象的问题:线程如何向UI线程或服务发送消息。 在您的情况下,您可以将Handler从WebService传递到WebServer;或从WebServer发送广播并由WebService接收