tags:

views:

23

answers:

1

I am using SmartFoxServer for a multiplayer game. I have it working fine when it loads up in the main chat room. In my app you an create new game rooms and when you click on one it launches a new activity and enters that room. It appears I have to connect to the server again after that. Then I get already logged in error.

How can I maintain the smartfox client throughout my activities?

A: 

You can override the Application class and make your server reference a static public variable which will be available from any Activity using ((YourApplication)getApplication()).yourStaticServerReference.

To override your Application class, follow the following steps :

  • Create a class extending Application, let's call it com.yourpackage.YourApplication

    package com.yourpackage;
    
    
    import android.app.Application;
    
    
    public class YourApplication extends Application {
        public static SmartFoxServer smartFoxServer;
    
    
    
        @Override
        public void onCreate() {
            smartFoxServer = initSmartFoxServer(); // I don't know SmartFoxServer's API so let's imagine you implement this somewhere in the Application class.
            // Now the smartFoxServer field is like a global variable visible in all your Activities using ((YourApplication)getApplication()).smartFoxServer
        }
    }
    
  • In your application manifest you have to edit the application declaration :

    <application android:icon="@drawable/icon" android:label="@string/app_name"
            android:name="com.yourpackage.YourApplication">
    

If you often access the smartFoxServer object, you can even use java 1.5 static import feature :

import static com.yourpackage.YourApplication.smartFoxServer;

public Activity myActivity {
    public void anyMethod() {
        // Thanks to the static import, smartFoxServer is directly accessible, without calling getActivity().
        smartFoxServer.doSomething();
    }
}

I wrote this directly here so there might be some things wrong... I will check this in more details when the kids let me more than 2 minutes of free time ;-)

Kevin Gaudin
I have read another solution like that. Currently my app uses two different tab activities. Where would I extend that application class at?
Adam Coburn
I quickly updated my answer with more details... so quickly that I might have missed something so I'll go back and check later if evrything is ok.
Kevin Gaudin
Thanks a ton. I implemented this and it looks like it is exactly what I was looking for. Thanks for helping me to understand the whole application extension concept
Adam Coburn
Glad to help, so please check your question as answered ;-)
Kevin Gaudin