First version that starts a permanently running HTTP server
[louyapi.git] / src / main / java / de / cweiske / ouya / louyapi / HttpService.java
diff --git a/src/main/java/de/cweiske/ouya/louyapi/HttpService.java b/src/main/java/de/cweiske/ouya/louyapi/HttpService.java
new file mode 100644 (file)
index 0000000..f5cc534
--- /dev/null
@@ -0,0 +1,58 @@
+package de.cweiske.ouya.louyapi;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.util.Log;
+
+import java.io.IOException;
+
+import fi.iki.elonen.NanoHTTPD;
+
+public class HttpService extends Service {
+    NanoHTTPD server;
+
+    static String TAG = "HttpService";
+
+    @Override
+    public void onCreate() {
+        Log.i("service", "start service");
+        super.onCreate();
+
+        server = new HttpServer(8080);
+        try {
+            server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
+        } catch (IOException ioe) {
+            //FIXME
+            Log.e(TAG, "Couldn't start server:\n" + ioe);
+            System.exit(-1);
+        }
+    }
+
+    @Override
+    public void onDestroy() {
+        Log.i(TAG, "stop service");
+        super.onDestroy();
+        server.stop();
+
+        //restart the service
+        sendBroadcast(new Intent(this, Autostart.class));
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        //android shall start the service again if killed
+        return START_STICKY;
+    }
+
+    @Override
+    public void onTaskRemoved(Intent rootIntent) {
+        Log.i(TAG, "Task removed");
+        super.onTaskRemoved(rootIntent);
+    }
+}
\ No newline at end of file