`

android Context上下文详细了解以及使用

 
阅读更多
1.Context基本概念

Context是什么

1) Context是一个抽象类,其通用实现在ContextImpl类中。

2) Context:是一个访问Application环境全局信息的接口,通过它可以访问application的资源和相关的类,其主要功能如下:

A.启动Activity
B.启动和停止Service
C.发送广播消息(Intent)
D.注册广播消息(Intent)接收者
可以访问APK中各种资源(如Resources和AssetManager等)
可以访问Package的相关信息
APK的各种权限管理

从以上分析可以看出,Context就是一个对APK包无所不知的大管家,大家需要什么,直接问它就可以了。

2.Context与View的关系
View与Context(或Activity)的关系类似于明星与经纪人的关系,所以创建View时,必须明确指定其Context(即经纪人或大管家),否则View就成不了明星。

Context家族关系:



Context类内容
public abstract class Context {

	// 获取应用程序包的AssetManager实例
	public abstract AssetManager getAssets();

	// 获取应用程序包的Resources实例
	public abstract Resources getResources();

	// 获取PackageManager实例,以查看全局package信息
	public abstract PackageManager getPackageManager();

	// 获取应用程序包的ContentResolver实例
	public abstract ContentResolver getContentResolver();

	// 它返回当前进程的主线程的Looper,此线程分发调用给应用组件(activities, services等)
	public abstract Looper getMainLooper();

	// 返回当前进程的单实例全局Application对象的Context
	public abstract Context getApplicationContext();

	// 从string表中获取本地化的、格式化的字符序列
	public final CharSequence getText(int resId) {
		return getResources().getText(resId);
	}

	// 从string表中获取本地化的字符串
	public final String getString(int resId) {
		return getResources().getString(resId);
	}

	public final String getString(int resId, Object... formatArgs) {
		return getResources().getString(resId, formatArgs);
	}

	// 返回一个可用于获取包中类信息的class loader
	public abstract ClassLoader getClassLoader();

	// 返回应用程序包名
	public abstract String getPackageName();

	// 返回应用程序信息
	public abstract ApplicationInfo getApplicationInfo();

	// 根据文件名获取SharedPreferences
	public abstract SharedPreferences getSharedPreferences(String name, int mode);

	// 其根目录为: Environment.getExternalStorageDirectory()
	/*
	 * @param type The type of files directory to return. May be null for the
	 * root of the files directory or one of the following Environment constants
	 * for a subdirectory: {@link android.os.Environment#DIRECTORY_MUSIC},
	 * {@link android.os.Environment#DIRECTORY_PODCASTS}, {@link
	 * android.os.Environment#DIRECTORY_RINGTONES}, {@link
	 * android.os.Environment#DIRECTORY_ALARMS}, {@link
	 * android.os.Environment#DIRECTORY_NOTIFICATIONS}, {@link
	 * android.os.Environment#DIRECTORY_PICTURES}, or {@link
	 * android.os.Environment#DIRECTORY_MOVIES}.
	 */
	public abstract File getExternalFilesDir(String type);

	// 返回应用程序obb文件路径
	public abstract File getObbDir();

	// 启动一个新的activity
	public abstract void startActivity(Intent intent);

	// 启动一个新的activity
	public void startActivityAsUser(Intent intent, UserHandle user) {
		throw new RuntimeException(
				"Not implemented. Must override in a subclass.");
	}

	// 启动一个新的activity
	// intent: 将被启动的activity的描述信息
	// options: 描述activity将如何被启动
	public abstract void startActivity(Intent intent, Bundle options);

	// 启动多个新的activity
	public abstract void startActivities(Intent[] intents);

	// 启动多个新的activity
	public abstract void startActivities(Intent[] intents, Bundle options);

	// 广播一个intent给所有感兴趣的接收者,异步机制
	public abstract void sendBroadcast(Intent intent);

	// 广播一个intent给所有感兴趣的接收者,异步机制
	public abstract void sendBroadcast(Intent intent, String receiverPermission);

	public abstract void sendOrderedBroadcast(Intent intent,
			String receiverPermission);

	public abstract void sendOrderedBroadcast(Intent intent,
			String receiverPermission, BroadcastReceiver resultReceiver,
			Handler scheduler, int initialCode, String initialData,
			Bundle initialExtras);

	public abstract void sendBroadcastAsUser(Intent intent, UserHandle user);

	public abstract void sendBroadcastAsUser(Intent intent, UserHandle user,
			String receiverPermission);

	// 注册一个BroadcastReceiver,且它将在主activity线程中运行
	public abstract Intent registerReceiver(BroadcastReceiver receiver,
			IntentFilter filter);

	public abstract Intent registerReceiver(BroadcastReceiver receiver,
			IntentFilter filter, String broadcastPermission, Handler scheduler);

	public abstract void unregisterReceiver(BroadcastReceiver receiver);

	// 请求启动一个application service
	public abstract ComponentName startService(Intent service);

	// 请求停止一个application service
	public abstract boolean stopService(Intent service);

	// 连接一个应用服务,它定义了application和service间的依赖关系
	public abstract boolean bindService(Intent service, ServiceConnection conn,
			int flags);

	// 断开一个应用服务,当服务重新开始时,将不再接收到调用,
	// 且服务允许随时停止
	public abstract void unbindService(ServiceConnection conn);

	// 返回系统级service句柄
	/*
	 * @see #WINDOW_SERVICE
	 * 
	 * @see android.view.WindowManager
	 * 
	 * @see #LAYOUT_INFLATER_SERVICE
	 * 
	 * @see android.view.LayoutInflater
	 * 
	 * @see #ACTIVITY_SERVICE
	 * 
	 * @see android.app.ActivityManager
	 * 
	 * @see #POWER_SERVICE
	 * 
	 * @see android.os.PowerManager
	 * 
	 * @see #ALARM_SERVICE
	 * 
	 * @see android.app.AlarmManager
	 * 
	 * @see #NOTIFICATION_SERVICE
	 * 
	 * @see android.app.NotificationManager
	 * 
	 * @see #KEYGUARD_SERVICE
	 * 
	 * @see android.app.KeyguardManager
	 * 
	 * @see #LOCATION_SERVICE
	 * 
	 * @see android.location.LocationManager
	 * 
	 * @see #SEARCH_SERVICE
	 * 
	 * @see android.app.SearchManager
	 * 
	 * @see #SENSOR_SERVICE
	 * 
	 * @see android.hardware.SensorManager
	 * 
	 * @see #STORAGE_SERVICE
	 * 
	 * @see android.os.storage.StorageManager
	 * 
	 * @see #VIBRATOR_SERVICE
	 * 
	 * @see android.os.Vibrator
	 * 
	 * @see #CONNECTIVITY_SERVICE
	 * 
	 * @see android.net.ConnectivityManager
	 * 
	 * @see #WIFI_SERVICE
	 * 
	 * @see android.net.wifi.WifiManager
	 * 
	 * @see #AUDIO_SERVICE
	 * 
	 * @see android.media.AudioManager
	 * 
	 * @see #MEDIA_ROUTER_SERVICE
	 * 
	 * @see android.media.MediaRouter
	 * 
	 * @see #TELEPHONY_SERVICE
	 * 
	 * @see android.telephony.TelephonyManager
	 * 
	 * @see #INPUT_METHOD_SERVICE
	 * 
	 * @see android.view.inputmethod.InputMethodManager
	 * 
	 * @see #UI_MODE_SERVICE
	 * 
	 * @see android.app.UiModeManager
	 * 
	 * @see #DOWNLOAD_SERVICE
	 * 
	 * @see android.app.DownloadManager
	 */
	public abstract Object getSystemService(String name);

	public abstract int checkPermission(String permission, int pid, int uid);

	// 返回一个新的与application name对应的Context对象
	public abstract Context createPackageContext(String packageName, int flags)
			throws PackageManager.NameNotFoundException;

	// 返回基于当前Context对象的新对象,其资源与display相匹配
	public abstract Context createDisplayContext(Display display);
}


3.何时创建Context

应用程序在以下几种情况下创建Context实例:

1) 创建Application对象时,而且整个App共一个Application对象

2) 创建Service对象时

3) 创建Activity对象时

因此应用程序App共有的Context数目公式为:

总Context实例个数 = Service个数 + Activity个数 + 1(Application对应的Context实例)

通过对ContextImp的分析可知,其方法的大多数操作都是直接调用其属性mPackageInfo(该属性类型为PackageInfo)的相关方法而来。这说明ContextImp是一种轻量级类,而PackageInfo才是真正重量级的类。而一个App里的所有ContextImpl实例,都对应同一个packageInfo对象。









  • 大小: 41.4 KB
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    Android中上下文(context)用法详解

    Context用法详解

    谈谈Android里的Context的使用

    //获取View的上下文. mContext = getContext(); //这里将Context转换为Activity. mActivity = (Activity)mContext; LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater....

    Android的context使用

    家好,今天给大家分享一下Android里的Context的...但是工具类还有View里没有这个上下文怎么办?为了解决大家的疑问,我今天写一个简单的Demo.让大家如何学好自如的用Context.想什么时候有Context,什么时候就有Context

    Android 为EditText文本框添加长按显示上下文菜单.rar

    Android ContextMenu实例,为EditText文本框添加上下文菜单,菜单激活并显示的方式是,用户在EditText输入框上面长按2秒,即可弹出上下文菜单,如运行截图所示的效果,为实现此功能,创建了onCreateContextMenu ...

    谈谈Android里的Context的使用实例

    但是工具类还有View里没有这个上下文怎么办?为了解决大家的疑问,为了解决大家的疑问,我今天写一个简单的Demo.让大家如何学好自如的用Context.想什么时候有Context,什么时候就有Context. 这里大致可以分为两种:一...

    WebView上下文菜单demo

    实现WebView的ContextMenu,自定义菜单功能,包括复制等功能。

    context-android:适用于Android的上下文应用

    语境适用于Android的上下文应用

    Android高级应用源码-ContextMenu 上下文选项菜单,长按后跳出菜单.rar

    源码参考,欢迎下载

    Android-Context-Menu.Android.zip

    Android-Context-Menu.Android.zip,你可以很容易地添加令人敬畏的动画上下文菜单到你的应用程序。,安卓系统是谷歌在2008年设计和制造的。操作系统主要写在爪哇,C和C 的核心组件。它是在linux内核之上构建的,具有...

    AndroidContext:Appcelerator Titanium js 库在 Android 上触发 pausedresumed 事件

    安卓上下文Appcelerator Titanium 代码在 Android 中触发暂停/恢复事件。如何使用将 Context.js 放在您的app/lib文件夹中,并使用 Android Context 注册每个活动: <Alloy><Window xss=removed xss=removed></Alloy>...

    Android Context初探

    Context中文意思是上下文,在小学语文课时,我们肯定接触过联系上下文理解词语的题目,“上下文”指的是语境,我们对语境的含义肯定是比较了解,一是小学刷那么多题目,二是现实生活中也常碰到,当你暗恋的对象对你...

    SuperToast:android的上下文感性祝酒词

    概述SuperToast是一个实用程序类,需要显示包装在实际上下文中的toast的 Android 开发人员可以使用它。 SuperToast 将显示在应用程序窗口的顶部位置。用法API 与 Toast API 一样简单。 创建实例: SuperToast ...

    上下文菜单

    是JAVA最常见的上下文菜单,在编程中最常遇到,也用了最简单的方式,让人看了一目了然。

    Android获取其他包的Context实例代码

    Context有个createPackageContext方法,可以创建另外一个包的上下文,这个实例不同于它本身的Context实例,但是功能是一样的。 这个方法有两个参数:1。packageName 包名,要得到Context的包名2。flags 标志位,有...

    Yalantis/Context-Menu.Android

    可以方便快速集成漂亮带有动画效果的上下文菜单

    Android-Context-Sensing-Framework:允许使用最少的代码监控上下文信息

    Android 上下文感知框架 一个简单的上下文监控框架,用于处理上下文感知和上下文信息轮询。 要监视特定上下文: ContextManager mContextManager = new ContextManager(getApplicationContext()); //...

    awareness-android:上下文规则

    目录目的此示例应用程序将向您展示如何通过自定义事件在上下文规则中使用提供的上下文对象,并通过 ContextHub SDK 中的触发事件开始运行这些上下文规则ContextHub 用例在此示例应用程序中,我们使用 ContextHub 在...

    深入解析Android App开发中Context的用法

    主要介绍了深入解析Android App开发中Context的用法,包括Context的创建场景和Context对资源的访问等内容,需要的朋友可以参考下

    Android代码-NavigationBar

    * @param context 上下文 * @param titles 标题栏 * @param viewPager * @param unselectedcolor 未选中字体颜色 * @param setectedcolor 选中字体颜色 * @param txtUnselectedSize 未选中字体大小 * @pa

    react-native-context-menu-view:在React Native中使用本地上下文菜单

    使用React Native的本地上下文菜单功能。 在iOS 13+上,它使用UIMenu功能,在Android上,它使用PopUpMenu 。 在iOS 12及更低版本上,没有任何React。 您可能希望执行Platform.OS === 'ios' && parseInt(Platform....

Global site tag (gtag.js) - Google Analytics