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
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.