Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application singleton use in Android

I have a facebook initialize sdk call and I need it to initialize the moment application is launched:

I want to use my Application class to do that. for example:

public class App extends Application {

@Override
public void onCreate() {
    super.onCreate();
    FacebookSdk.sdkInitialize(getApplicationContext());
}
}

I have the main activity with the facebook login button:

public class MainActivity extends AppCompatActivity {
@BindView(R.id.login_button)
LoginButton loginButton;

private CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    callbackManager = CallbackManager.Factory.create();
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    });
}
}

How do I call my Application singleton? How do I make its onCreate() work?

like image 974
Ackman Avatar asked Nov 28 '22 20:11

Ackman


2 Answers

When you extend android.app.Application class, you do not have to call onCreate explicitly. But make sure you specify it in AndroidManifest.xml, like this android:name="fully-qualified name" eg: android:name="com.example.MyApplication"

You don't have to implement Singleton pattern cause Application IS ALREADY A SINGLETON, there is only one instance of your Application. And, to get the instance of Application or the any custom child of Application you defined, you can simply call context.getApplication().

Reference https://developer.android.com/reference/android/app/Application.html

like image 52
Seeker Avatar answered Dec 05 '22 10:12

Seeker


To make your App class singleton follow the Singleton design pattern:

public class App
  {
    // Create the instance
    private static App instance;
    public static App getInstance()
    {
         if (instance== null) {
                synchronized(App.class) {
                        if (instance == null)
                                instance = new App();
                        }
                }
                // Return the instance
                return instance;
    }

    private App()
    {
        // Constructor hidden because this is a singleton
    }

    public void initFBSdk()
    {
        FacebookSdk.sdkInitialize(getApplicationContext());
    }
}

Then to use it in any other class:

App.getInstance().initFBSdk();

If this is what you are asking for..

like image 32
Anmol Avatar answered Dec 05 '22 11:12

Anmol