在Android中获取Application实例的正确方法 [英] Correct way to get the instance of Application in android
问题描述
以下哪种方式更适合获取Application实例
Which of these ways is more proper for getting the instance of Application
-
初始化Application.onCreate()中的静态字段并提供对其的静态访问
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();
}
}
创建将Context作为参数的静态方法,并将该上下文转换为MyApplication
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);
}
}
推荐答案
如果您仅需要应用程序的实例,我将推荐方法3.
I would recommend method 3 if you only need the instance of the Application.
如果您的Application类中还有其他方法,我建议使用方法1,因为您可以更清楚地进行
I would recommend method 1 if you had additional methods in your Application class because you can more clearly do
MyApplication.getInstance().foo();
方法2只是方法3的快捷方式,因此我不推荐使用.
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.
这篇关于在Android中获取Application实例的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!