Tiago
Tiago

Reputation: 1116

How to maintain Server Socket through Activities?

In my application I decided to make a server and client through Sockets (just testing my idea for now).

So I made two AsyncTasks (for the server and client) an on my onCreate (depending on user action - as I said I'm just testing, for now just with buttons):

new createServer().execute(); 

or

new connectClient().execute();

Question is, everything works good, but the app where I want to implement my idea has many activities, so the app that is serving the data, when leave the activity where the createServer Async Task is, the client (obviously) loses the connection.

Is there a way to maintain the server running "all time", and allow the user (with the "server app") to navigate through the app without affecting the connected clients? Because even if everytime I leave an activity I create the Server, the clients will lose connection anyway.

Really appreciate any suggestion.

EDIT: For the purposes of my test application, I need the system to be working only in foreground, no background, so no need of service creation.

Upvotes: 1

Views: 1673

Answers (1)

kabuko
kabuko

Reputation: 36302

Your problem is with correctly managing the lifetime of your server. First you'll have to decide what you want that lifetime to be. Clearly you've figured out that you want it to be broader than just the activity level, but do you want it to run in the background or only when your app is in the foreground? If it is only when in the foreground, you can get away with not creating a service, but instead keeping a reference to a component from your application object. However, if you want to keep your server running even when your app is in the background you do need a Service.

Update:

Here's an example of what I meant by "keeping a reference to a component from your application object":

  • Create a custom Application class.
  • Add a field to hold a reference to your server AsyncTask

    private AsyncTask mServerTask;
    
  • Add a method to it to start your server AsyncTask

     public void startServer() {
         mServerTask = new createServer();
         mServerTask.execute();
     }
    
  • Probably add another method to stop your server

To start your server from an activity you can now do something like:

CustomApplication app = (CustomApplication) getApplication();
app.startServer();

Of course you'll want to do more to properly manage the server like making sure you don't start it twice, etc. and you might decide to use threads instead of AsyncTasks but this should give you an idea of how you can have an object with a lifetime beyond that of an activity.

Upvotes: 4

Related Questions