下面是我使用NanoHTTPD編寫的一個相當簡單的應用程序的代碼。 它被稱爲'ClockServer',因爲我在數字時鐘應用程序中使用它,以便可以遠程設置時鐘的數字顏色,背景顏色和亮度。
我在我的應用程序的Application子類中實例化ClockServer類。 正如你所看到的,serve
方法返回它的結果,像這樣:
return new NanoHTTPD.Response(Response.Status.OK, MIME_JSON, responseString);
這裏的ClockServer類:
import android.content.res.Resources;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import fi.iki.elonen.NanoHTTPD;
public class ClockServer extends NanoHTTPD {
private static final String MIME_JSON = "application/json";
private Clock clock;
public ClockServer(Clock clock, int port) {
super(port);
this.clock = clock;
}
@Override
public Response serve(IHTTPSession session) {
try {
Method method = session.getMethod();
String uri = session.getUri();
Map<String, String> parms = session.getParms();
String responseString = serveClock(session, uri, method, parms);
return new NanoHTTPD.Response(Response.Status.OK, MIME_JSON, responseString);
} catch (IOException ioe) {
return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
} catch (ResponseException re) {
return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
} catch (NotFoundException nfe) {
return new NanoHTTPD.Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found");
} catch (Exception ex) {
return new Response(Response.Status.INTERNAL_ERROR, MIME_HTML, "<html><body><h1>Error</h1>" + ex.toString() + "</body></html>");
}
}
private String serveClock(IHTTPSession session, String uri, Method method, Map<String, String> parms) throws IOException, ResponseException {
String responseString = "";
do {
if(Method.GET.equals(method)) {
responseString = handleGet(session, parms);
break;
}
if(Method.POST.equals(method)) {
responseString = handlePost(session);
break;
}
throw new Resources.NotFoundException();
} while(false);
return responseString;
}
private String handleGet(IHTTPSession session, Map<String, String> parms) {
return clock.handleRequest("{'name':'status', 'value':''}");
}
private String handlePost(IHTTPSession session) throws IOException, ResponseException {
Map<String, String> files = new HashMap<String, String>();
session.parseBody(files);
return clock.handleRequest(files.get("postData"));
}
private class NotFoundException extends RuntimeException {
}
}
請問您的時鐘服務器會一直工作?即使你的應用程序被殺害? –