Getting Force Close when starting Android Service (as Server Socket)
<p>I have an application with many activities, and "behind" the application I want a server socket always running, listening and serving data on request.</p>

<p>So I've created a service, but maybe I'm not understanding how it works because I'm having some problems. Let's see my service:</p>

<pre><code>public class MyService extends Service {
    private static final String TAG = "MyService";  
    @Override   
    public IBinder onBind(Intent intent) {  
        return null;    
    }       
    @Override   
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d("STATUS", "onCreate service");    

        try {


            // create socket
            ServerSocket servsock;
            servsock = new ServerSocket(50000);
            Log.v("STATUS","SERVER SOCKET CREATED at="+50000);


while (true) {
                Log.v("status","Waiting..."); 

                Socket sc = servsock.accept();
                Log.v("status","Accepted connection : " + sc);

                ObjectOutputStream os =  new ObjectOutputStream(sc.getOutputStream());
                ObjectInputStream is = new ObjectInputStream(sc.getInputStream());
                .........
                sc.close();

            }

.............
</code></pre>

<p>In my app the first screen appearing it's a login screen, and I want the service to start imediatelly after the login (on creation of the "logged in" activity)</p>

<pre><code>public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainActivity);

        startService(new Intent(this, MyService.class));
........
</code></pre>

<p>Problem is, when the activity starts I get a Force Close above a black screen (interesting because the startService is after the setContentView) - although I can see through the Logcat that the service (and the server socket) was executed.</p>

<p>The activity manager gives me the following information:</p>

<blockquote>
  <p>01-10 17:55:43.706: E/ActivityManager(2490): ANR in
  com.sapo.android.obesidade 01-10 17:55:43.706:
  E/ActivityManager(2490): Reason: Executing service
  com.sapo.android.obesidade/.MyService 01-10 17:55:43.706:
  E/ActivityManager(2490): Load: 1.24 / 1.13 / 1.1 01-10 17:55:43.706:
  E/ActivityManager(2490): CPU usage from 43658ms to 10ms ago: 01-10
  17:55:43.706: E/ActivityManager(2490):   system_server: 6% = 3% user +
  3% kernel / faults: 7590 minor 01-10 17:55:43.706:
  E/ActivityManager(2490):   .app.twlauncher: 2% = 2% user + 0% kernel /
  faults: 812 minor 01-10 17:55:43.706: E/ActivityManager(2490):<br>
  mmcqd: 0% = 0% user + 0% kernel</p>
</blockquote>

<p>So the problem is undoubtedly (it works if removed) on the while(true) - something that was already working in an AsyncTask in an Activity (without using Services). </p>

<p>What can I do ?</p>
