哪种方法更适合获取Application实例?
在Application.onCreate()中初始化静态字段并提供静态访问
创建一个静态方法,该方法接受Context作为参数,并将该Context转换为MyApplication。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(); } }
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); } }
BroadcastReceiver
中使用Context
,那么onReceive(Context context,...)
已经作为第一个参数提供了。请使用它。 - M D