当前位置:首页 > 数码 > Context在Android开发中的至关重要性 (contextual)

Context在Android开发中的至关重要性 (contextual)

admin4个月前 (05-01)数码38

Introduction

In Android development, Context is a crucial class that represents the current environment in which an application is running. It can be understood as an interface to global information, providing access to application resources, system services, and serves as a key to launching other components and creating user interfaces.

The main roles of the Context class are:

  1. Accessing application resources (e.g., strings, layouts, drawables)
  2. Accessing system services (e.g., network, location, sensors)
  3. Launching other application components (e.g., activities, services, broadcasts)
  4. Creating user interfaces (e.g., layouts, views, menus)

Structure of Context

The Context class plays a vital role in Android development by providing access to the application's environment, enabling convenient resource access, and serving as an interface for various operations.

public abstract class Context {
    // Get the application's package name
    public abstract String getPackageName();

    // Get the application's resource manager
    public abstract Resources getResources();

    // Get the application's database manager
    public abstract SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory);

    // Get the application's SharedPreferences object
    public abstract SharedPreferences getSharedPreferences(String name, int mode);

    // Get the application's AssetManager object
    public abstract AssetManager getAssets();

    // Get the application's ClassLoader object
    public abstract ClassLoader getClassLoader();

    // Get the application's theme
    public abstract Theme getTheme();

    // Get the application's package manager
    public abstract PackageManager getPackageManager();

    // Get an application's system service by name
    public abstract Object getSystemService(String name);

    // ...
}

The Context class is an abstract class that cannot be directly instantiated. However, it can be obtained from instances of classes like Activity , Service , or Application .

1. ContextImpl Class

The ContextImpl class is one of the concrete implementations of Context . The Context interface is a global information interface for Android applications, providing methods to access application resources and perform application operations. The ContextImpl class is primarily responsible for managing the application's resources and providing the environment in which the application runs. It contains a range of vital methods, such as getResources() for retrieving the application's resources, startActivity() for starting a new Activity , getSystemService() for accessing system services, and more.

The ContextImpl class plays a crucial role in Android application development, offering a plethora of application-related methods and functionality, allowing developers to conveniently access and manipulate application resources and environment.

2. ContextWrapper Class

The ContextWrapper class is a wrapper class for the Context class. The ContextWrapper class extends the Context class and implements all the methods in the Context interface. Its main purpose is to facilitate the extension and customization of existing Context objects.

With the ContextWrapper class, we can wrap the original Context object and then add custom functionality or modify existing functionality in the wrapper class. This enables the extension of Context object functionality without the need to modify the original Context class.

Context在Android开发中的至关重要性

Commonly used methods of the ContextWrapper class include:

  • ContextWrapper(Context base) : Constructor that takes an existing Context object as input and wraps it.
  • Context getBaseContext() : Returns the wrapped Context object.
  • public abstract Object getSystemService(String name) : Overriding the getSystemService() method allows for custom handling of system service retrieval.

The ContextWrapper class is a wrapper class used in Android to extend and customize Context objects, providing commonly used methods for accessing application resources and performing application operations.

Conclusion

The Context class is a fundamental component in Android development, providing a comprehensive interface for accessing application-related information and performing various operations. It serves as a crucial tool for developers to interact with the application environment, manage resources, and create robust and user-friendly applications.


Context是什么

ContextContext,翻译是上下文环境,在android应用开发中的地位举足轻重,甚至源码也有一句话:everything needs a context(看到过,但是忘了在哪里了)。 从这个类图中我们看到,Context是一个抽象类,一边是Context的具体实现ContextImpl,一边则是组件的封装类ContextWrapper,便于二者各司其职,我理解是接口和实现分开,这样比较符合开闭原则吧。 既然要搞清楚Context是干嘛的,得先看Context的实例什么时候创建的。 这里有两个我们经常接触的组件,Activity和Service,以及用的较少的Application,它们的关系如下: :保存应用的全局信息的类,它的实例在应用创建的时候被创建,生命周期最长,应用销毁了才会被销毁。 :创建一个Activity便对应一个Context的实例,生命周期随着Activity的周期变化。 :创建一个Service便对应一个Context的实例,生命周期随着Service的周期变化。 下面逐一看看它们是什么时候实例Context类的,我们需要知道,一个ContextWrapper类对应一个ContextImpl类的实例,因为具体实现的地方还是在ContextImpl中,ContextWrapper中的mBase变量指向ContextImpl变量的实例。 (1) Application的Context创建:如图: 跳过Process创建过程,在我们的应用被zygote进程孵化出来后,被反射调用main函数,这里会创建ActivityThread类的实例,该类并不是一个线程类的子类,但是它的main函数跑在新创建的进程的主线程。 创建后,调用attach方法,与AMS绑定:这里传入的mAppThread变量为ApplicationThread类,它为ActivityThread的内部类,作用就是作为应用端的binder服务端,负责接收AMS的调度,这里我们传入这个服务端的句柄,让AMS持有,从而AMS可以通过这个句柄来操控应用的行为。 我们向AMS请求,则是通过AMS的句柄。 接下来就到了AMS的逻辑:在ApplicationThread的实现端中,就是把跨进程传递过来的各种数据再用一个AppBindData类保存下来,然后调用Handler对象H发送消息BIND_APPLICATION,最后在app线程中处理此逻辑,让AMS线程可以不必同步阻塞。 接下来就到了handleBindApplication:Instrumentation类是用于管理Acitivty的工具类。 这又有一个比较重要的对象出现,LoadedApk,它里面保存了类加载器ClassLoader,的对象便是它,makeApplication函数中的逻辑: 这里我们看到了ContextImpl的创建时机,就是在Application实例创建的时候: 如此就完成了Application的创建,并且调用attach方法把Application的mBase对象赋值给创建的ContextImpl,至此Application的创建就完成了,getApplicationContext() 返回的便是此处我们创建的Application类的对象。 这里为什么要去LoadedApk类中利用类加载器,把对象创建出来呢?因为我们的Application类是可以自己拓展的,创建的时候是不确定应用自己是否复写了Application对象, 利用类加载器就可以动态决定创建什么类的对象了 ,我们只需要从PMS中获取到application的具体类名即可,这个类名是写在Mainfest文件中的,后面Activity也是利用这种机制去创建对象。 (2)Actvity的启动过程,网上非常多文章分析了,我也就不再重复罗列出来了,大概的过程就是startActivity()被调用,然后检查目标Acitivity的进程是否创建,没创建就先向Zygote进程请求fork应用进程,然后一系列初始化过程后,最后在AMS模块中的ActivityStackSupervisor中realStartActivityLocked()调用IApplicationThread代理类,调用到scheduleLaunchActivity(),然后在应用的线程开始执行handleLaunchActivity(),最主要的逻辑在performLaunchActivity: 至于Activity的生命周期后面怎么走的,这里不在乎,我们只看Context实例化过程。 同样的,这里也会创建ContextImpl对象,在Activity对象创建后,调用Attach(),这个函数挺重要的,我们看看都干了什么: 在attach函数中,也会为ContextWrapper中的mBase对象赋值一个ContextImpl对象,我们这里也能猜想到Service的创建估计也会有这个过程,而事实上Service的创建差不多也是这个过程,所以不再赘述了。 我们可以知道Context例的实例化都是在我们在Application,Activity和Service创建的时候会实例化,而这些组件的父类都是ContextWrapper,所以在创建的时候还会先创建一个ContextImpl类对象,然后给自己的父类mBase变量赋值,既然如此,Context的引用对应的就是Application,Activity和Service了,Context的用处就是提供了一组抽象的函数,让子类去相对应的实现,当你持有一个Context引用的时候,你可以通过这个引用去获取相对应组件的信息。 比如持有一个Activity的Context引用,你可以在别的地方调用startActivity()去启动一个新的activity。 总结是抽象类,所以实例化要在子类中,Application,Service,Activity是我们实例化的地方,一般应用创建会实例化一个Application类,Service和Activity则是在startService和StartActivity被调用的时候会实例化,它们都会创建一个ContextImpl类实例,给自己的父类ContextWrapper的mBase变量赋值。 是组件中通用操作的一组集合,当具体的子类实例化后,可以在别的地方通过保存一个Context引用去获取信息和通用操作等,也就是说,我们可以通过这个引用去获取到这个应用中的重要信息以及这个应用的通用操作。

android context是什么

Context字面意思是上下文,位于framework package的中,其实该类为LONG型,类似Win32中的Handle句柄。 很多方法需要通过 Context才能识别调用者的实例:比如说Toast的第一个参数就是Context,一般在Activity中我们直接用this代替,代表调用者的实例为Activity,而到了一个button的onClick(View view)等方法时,我们用this时就会报错,所以我们可能使用来解决,主要原因是因为实现Context的类主要有Android特有的几个模型,Activity以及Service。 Context提供了关于应用环境全局信息的接口。 它是一个抽象类,它的执行被Android系统所提供。 它允许获取以应用为特征的资源和类型。 同时启动应用级的操作,如启动Activity,broadcasting和接收intents。

免责声明:本文转载或采集自网络,版权归原作者所有。本网站刊发此文旨在传递更多信息,并不代表本网赞同其观点和对其真实性负责。如涉及版权、内容等问题,请联系本网,我们将在第一时间删除。同时,本网站不对所刊发内容的准确性、真实性、完整性、及时性、原创性等进行保证,请读者仅作参考,并请自行核实相关内容。对于因使用或依赖本文内容所产生的任何直接或间接损失,本网站不承担任何责任。

标签: Android

“Context在Android开发中的至关重要性 (contextual)” 的相关文章

在Android运行开发中应用NFC配置 (在android中使用menu时可能需要重写的方法有)

在Android运行开发中应用NFC配置 (在android中使用menu时可能需要重写的方法有)

NFC引见 NFC是指近场通讯(NearFieldCommunication),它是一种短距离无线通讯技术,准许设施在非接触或极短距离内启动通讯。NFC通罕用于移动支付、门禁系统、默认标签和...

Android中保持屏幕常亮的有效方法-全面指南 (android studio)

Android中保持屏幕常亮的有效方法-全面指南 (android studio)

WakeLock是Android中用于控制设备唤醒状态的类。通过获取WakeLock对象并设置屏幕常亮标志,可以保持屏幕常亮。这对于需要在设备处于休眠状态时仍然保持屏幕显示的应用程序非常有用,例如...

Android发热监控通常指南 (android是什么)

Android发热监控通常指南 (android是什么)

在此也只是粗略引见以后曾经做的针对发热控制的一些初步上班,以及对未来发热功耗相关展开的思绪,宿愿能让带来更好的体验,给用户带来更对美妙事物的向往的感触。​ 一、背景 置信移动端高度遍及的如今...

Android数据对象序列化原理与运行 (android是什么)

Android数据对象序列化原理与运行 (android是什么)

序列化与反序列化 「序列化」是将对象转换为可以存储或传输的格局的环节。在计算机迷信中,对象通常是指内存中的数据结构,如数组、列表、字典等。经过序列化,可以将这些对象转换为字节流或文本格局,以...

结构和应用-深入了解Android中的SELinux-了解其功能 (茶多酚的结构和应用)

结构和应用-深入了解Android中的SELinux-了解其功能 (茶多酚的结构和应用)

SELinux 简介 SELinux(Security-Enhanced Linux)是一种安全增强的 Linux 操作系统,它通过强制访问控制 (MAC) 机制来提供更高级别的系统安全保护...

从单一进程到模块化设计-Android-架构演进历程 (单进程系统)

从单一进程到模块化设计-Android-架构演进历程 (单进程系统)

Android architecture has undergone multiple evolutions, from the initial traditional MVC architect...

AIDL在Android运行程序开发中的关键性

AIDL在Android运行程序开发中的关键性

DL引见 AIDL(InterfaceDefinitionLanguage)是一种用于定义Android运行程序中的跨进程通讯接口的言语。经过经常使用AIDL,开发人员可以定义客户端和服务之...