I have a simple web server which serves only music files from storage to be consumed over a network.
At present it stops responding to requests if the phone is locked or it goes to sleep. While researching I came to know the solution for that is to push the service in AsyncTask.
But then when I went through this SO post, it mentions that AsyncTask basically is for one-off tasks, be done with it.
So does it mean I can't run a webserver, since it will be waiting for incoming requests?
I have seen in my phone the native Music player never stops the whole night, even when back is pressed or screen is locked. It keeps running. So it is possible to achieve this with the server as well? How can we do that?
My code so far
public class MainActivity extends AppCompatActivity {
public Mp3Server server;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server = new Mp3Server();
try {
server.start();
} catch(IOException ioe) {
Log.w("Httpd", "The server could not start.");
}
Log.w("Httpd", "Web server initialized.");
}
@Override
public void onDestroy()
{
super.onDestroy();
if (server != null)
server.stop();
}
public class Mp3Server extends NanoHTTPD {
public Mp3Server() {
super(8089);
}
@Override
public Response serve(String uri, Method method,
Map<String, String> header, Map<String, String> parameters,
Map<String, String> files) {
String answer = "";
Log.w("HTTPD", uri);
Log.w("HTTPD", parameters.toString());
Log.w("HTTPD", "Method is: "+method.toString());
Log.w("HTTPD", "Header is: "+header.toString());
FileInputStream fis = null;
try {
fis = new FileInputStream("/storage/C67A-18F7/"
+ "/Music/"+uri);
Log.w("HTTPD", uri + " found");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newChunkedResponse(Status.OK, "audio/mpeg", fis);
}
}
}