Which of these ways is more proper for getting the instance of Application
Initialise static field in Application.onCreate() and provide static access to it
public class MyApplication extends Application {
private static MyApplication sInstance;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static MyApplication getInstance() {
return MyApplication.sInstance;
}
}
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MyApplication application = MyApplication.getInstance();
}
}
Create static method which takes Context as param and cast that Context to MyApplication
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
}
public static MyApplication getInstance(Context context) {
return ((MyApplication) context.getApplicationContext());
}
}
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MyApplication application = MyApplication.getInstance(context);
}
}
getInstance(String algorithm) The getInstance() method of java. security. Provider class is used to return a Signature object that implements the specified signature algorithm. This method traverses the list of registered security Providers, starting with the most preferred Provider.
You can go for getApplicationContext() if you wanna get context of whole application. If you want to get context of current class you can use getBaseContext() instead.
Overview. The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.
Open AndroidManifest. xml file of your app and locate <application> tag. Add an attribute android:name and set it to your new application class.
I would recommend method 3 if you only need the instance of the Application.
I would recommend method 1 if you had additional methods in your Application class because you can more clearly do
MyApplication.getInstance().foo();
Method 2 is just a shortcut for method 3, so I wouldn't recommend it.
All in all, it's a matter of preference. There is no one "correct" way because they'll all work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With