1

I have an activity with included webserver-class (simplified):

public class MyActivity extends AppCompatActivity {

    SimpleWebServer webServer = new SimpleWebServer(8088);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
    }

    @Override protected void onResume() {
        super.onResume();
        // Starting webserver
        try {
            webServer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void changeActivityButtonClicked(View view){
        //change activity
    }

    public void disconnectButtonClicked(View view){
        // Stopping webserver
        webServer.stop();
    }

    //Webserver-Class
    private class SimpleWebServer extends NanoHTTPD {
        public static final String TEXT_404 = "404 File Not Found";

        public SimpleWebServer(int port) {
            super(port);
        }

        @Override
        public Response serve(IHTTPSession session) {
            return new Response("You didn't use the API");
        }
    }
}

This code works as expected when I don't leave the activity. But when I exit this activity (via the changeActivityButtonClicked()-method or whatever) and re-enter it, I can't use the webServer.stop() command anymore. The server runs forever.

I guess I'm loosing focus of the actual webServer-object when changing the activity, but I have no idea how to reaccess it.

Do you have any hints?

Cologne_Muc
  • 653
  • 6
  • 19
  • Anything in the logcat? Nothing done in `onPause()` or `onDestroy()` to stop the webserver? – shkschneider Jul 02 '15 at 15:44
  • I don't want to stop the webserver when I leave the activity on normal ways (back, home, ...), therefore no stop in `onPause()` etc. Only by clicking this button. And no, nothing in logcat. I can log "Server stopping..." immediately before the `webServer.stop()` command, but it is still running (I check that for example via Browser in the LAN) – Cologne_Muc Jul 03 '15 at 05:23
  • I got to see Logcat-Output (http://daniel-betz.de/logcat.txt) Seems, that the activity tries to start a second webserver (Error: EADDRINUSE). Unfortunately I can't prevent from starting it, because `if(webServer.isAlive())` is always false... – Cologne_Muc Jul 03 '15 at 06:02
  • Your server is still running if you get `EADDRINUSE`, whatever `isAlive()` says. – shkschneider Jul 03 '15 at 08:02

0 Answers0