How to create nanohttpd server in android?

后端 未结 4 1505
情话喂你
情话喂你 2021-02-09 05:10

Actually ,I had searched some questions and go to the github. But I\'m new ,I cannot understand the example.

I want to create the http server in android so I can access

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-09 06:05

    Android Activities have a lifecycle and do not use a main() function.

    If you want to start and stop the webserver as part of the Activity then you need call start and stop in onPause and onResume, ie

    public class MyActivity extends Activity {
    
        private MyHTTPD mServer;
    
        @Override
        protected void onResume() {
            super.onResume();
    
           try {
                mServer = new MyHTTPD();
                mServer.start();
            } catch (IOException e) {
                e.printStackTrace();
                mServer = null;
            }
    
    
        @Override
        protected void onPause() {
            super.onPause();
            if(mServer != null) {
                mServer.stop();
                mServer = null;
            }
        }
    }
    

    An alternative is to implement the webserver as part of a Service.

    In an app I'm working I have a requirement to keep the webserver running even if the user leaves the app. The only way to do this is to start and stop the webserver as part of a long-running Service that is not bound to the Activity. See Vogella's great tutorial on Android Services.

提交回复
热议问题