1

I wrote an app that implements a web server with multithreading. The main activity has a button to start/stop a thread. When the server is powered on, this thread stays in listening and, if there is a request it creates a new thread to serve it. The app works fine, but now I would use a service instead, so it can work in background.

Actually I've this design (semplified):

WebServer.java

class WebServer implements Runnable{
protected Thread t;

 public void start(){
  ON=true;
  t=new Thread(this,"WebServer");
  t.start();
 }

 public void stop(){
 ON=false;
 t=null;}

 public void run(){
 while(ON)
 ...
 }

 public isOn(){
  return ON;
 }
}

DroidServer.java

class DroidServer extends WebServer{
...
}

MyActivity.java

public class MyActivity extends Activity{
ws = new DroidServer(8080,this);
btn.setOnClickListener(new OnClickListener(){
 public void onClick(View V){
    if(!ws.isOn()){
     ws.start();
     btn.setText("Stop");
    }else{
     ws.stop();
     btn.setText("Start");
    }}});
}

What should I change, to make it use Services? I'd like to extends Service from DroidServer, but this class already extends WebServer... any solutions?

supergiox
  • 1,586
  • 7
  • 19
  • 27

1 Answers1

2

Service is not a replacement for a Thread. Per definition from Service :

Most confusion about the Service class actually revolves around what it is not:

  • A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
  • A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

What you should do it create a Service then have your DroidServer run in the Service as a separate Thread so it could accept request in the background

momo
  • 21,233
  • 8
  • 39
  • 38
  • Hm.. I've a doubt: In this way (with a service that creates a thread), could Android System destroy this thread? Or is it "protected" by the Service? – supergiox Sep 01 '11 at 21:36
  • 1
    No, you should control how the Thread is stopped similar to what you did in your Activity. A Service is just basically just a way for Android to facilitate background process (i.e application process without user's interaction) – momo Sep 01 '11 at 21:41
  • Ok! Can I pass parameters to the Service? In my case the activity passes a reference of itself to DroidServer `ws = new DroidServer(8080,this);` – supergiox Sep 01 '11 at 21:48
  • Yes, you could pass the parameter via Intent as this question illustrate http://stackoverflow.com/questions/3293243/android-pass-data-from-activity-to-service-using-an-intent – momo Sep 01 '11 at 21:56
  • Thank you very much! I'll do as you suggested – supergiox Sep 01 '11 at 22:05