Search code examples
androidsocketstcpbackground-process

How can I keep my app running in the background?


I am creating an application in which I need to always be connected via a TCP socket. My application already works well in terms of the connection, but when it gets sent to the background, the android system eventually kills the process. This causes it to become disconnected from the server.

I've been looking for a way to always keep the application alive, but haven't found anything. Could someone tell me what would be the best way to make it so that my application is not closed when it's in the background, or, barring this, make it restart itself if it is closed? I'm starting with this and is producing me a headache :S

EDIT This is part of my code:

  public int onStartCommand(Intent intent, int flags, int startId) {

      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      new Thread(new Runnable() { 
            public void run() {
                Playit();               }
        }).start();


     return START_STICKY;
  }

The app appears to be frozen on startup, though. I do not have a lot of experience, so maybe my mistake is simple and I haven't noticed it.


Solution

  • Use a Service and start it via startService(). It will run until Android stops it for resources

    Some documentation on services:

    1. http://developer.android.com/reference/android/app/Service.html
    2. http://developer.android.com/guide/components/services.html