[英]ModelLayer(Context appContext) Singleton Constructor in Android…what does the following code with comments exactly do?
In the model layer of the Android project I am learning from the Big nerd Ranch Android Programming book, there is a specific singleton - model layer class, which goes like this: 在我从Big nerd Ranch Android编程书中学习的Android项目的模型层中,有一个特定的单例-模型层类,其内容如下:
public class ModelLayerClass
{
private static ModelLayerClass class_instance; //its a clear singleton here !
private Context context_instance;
private ModelLayerClass(Context appContext) //why this parameter is being passed?
{
context_instance = appContext; //how this helps here ?
}
public static ModelLayerClass get(Context c)
{
if(class_instance=null)
{
class_instance = new ModelLayerClass(c.getApplicationContext());
}
return class_instance;
}
}
When I went through the book, it was saying that, it is common practice in Android to have a Context parameter which allows the singleton to "start activities", access project resources, find your apps private storage and more.....doesnt the classes in our project have a default access to all of these (except for starting activities). 当我读完这本书时,有人说,在Android中,通常有一个Context参数,该参数允许单身人士“开始活动”,访问项目资源,查找应用程序的私有存储等等。我们项目中的类对所有这些类均具有默认访问权限(开始活动除外)。 Can anyone direct me to proper online resources or could give me a good explanation about this...thnx :)
任何人都可以将我定向到适当的在线资源,或者可以给我有关此问题的很好的解释... thnx :)
From your activity, you do have access to everything within your application, but generally through the use of context. 从活动中,您确实可以访问应用程序中的所有内容,但通常可以使用上下文。 Here's the Android documentation for Context .
这是Context的Android文档。
For example, when you write 例如,当你写
startActivity(new Intent(MainActivity.this, NewActivity.class));
You only have access to the startActivity method because your Activity class is extends Activity. 您只能访问startActivity方法,因为您的Activity类是对Activity的扩展。 If you want to start an activity from a singleton or from another class or anything like that, you need to have a Context to start an activity.
如果要从单例或其他类或类似的东西开始活动,则需要具有上下文才能开始活动。
For example, if you wanted to start the same activity above, but from outside of your Activity class, you must have a context: 例如,如果您想从上方开始同一活动,但要从Activity类外部开始,则必须具有上下文:
context.startActivity(new Intent(context, NewActivity.class));
Same goes for any number of other things you might want to do outside of your Activity class. 在Activity类之外可能要执行的其他任何其他操作也是如此。
Accessing resources: 访问资源:
Bitmap imageFromRes = BitmapFactory.decodeResource(context.getResources(), R.drawable.image);
Creating new Android views: 创建新的Android视图:
ImageView iv = new ImageView(context);
Basically, Context is a good "catch-all" parameter that allows your non-Android classes to still utilize methods that you would use in Android classes (like Activity, Service, Dialog, etc). 基本上,Context是一个很好的“包罗万象”参数,它允许您的非Android类仍然使用您将在Android类中使用的方法(例如Activity,Service,Dialog等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.