Android源码——Contxt和ContextWrapper源码解析

Contxt源码分析

  • Context
    • 继承结构
    • 常量
      • I/O 相关
      • bindService()相关
      • getSystemService相关
      • createPackageContext相关
    • 方法
      • Resources相关
      • context相关
      • Theme相关
      • Attributes相关
      • Package相关
      • SharedPreferences相关
      • I/O相关
      • 数据库相关
      • Wallpaper相关
      • Activity相关
      • IntentSender相关
      • Broadcast相关
      • Service相关
      • Permission相关
      • UriPermission相关
      • 其他
  • ContextWrapper

Context

继承结构

public abstract class Context {
}

常量

I/O 相关

用于openFileOutput()获取I/O流,或getSharedPreferences()获取SharedPreferences

  • private:创建的文件只能由该调用程序访问(或同一user ID程序)
  • readable/writeable:创建的文件所有程序可读/写(不安全)
  • append:向已存在文件的末尾追加
public static final int MODE_PRIVATE = 0x0000;
public static final int MODE_WORLD_READABLE = 0x0001;
public static final int MODE_WORLD_WRITEABLE = 0x0002;
public static final int MODE_APPEND = 0x8000;

设置此标志位,文件改动会被check,用于多线程操作SharedPreferences

public static final int MODE_MULTI_PROCESS = 0x0004;

用于openOrCreateDatabase()创建提前写入日志的数据库

public static final int MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x0008;

bindService()相关

  • 当需要绑定时启动服务
  • 用于调试不匹配的unbind调用,打印调用栈
  • 不让服务拥有前台调度优先级
  • 服务相比其宿主程序更为重要,内存不足时优先杀程序
  • 允许服务宿主程序进行内存管理
  • 不影响服务宿主程序的时间片调度和内存管理
  • 服务很重要,应提升至前台进程级别
  • 服务通过Activity启动,允许提升其重要性
  • 两个保留字段
public static final int BIND_AUTO_CREATE = 0x0001;
public static final int BIND_DEBUG_UNBIND = 0x0002;
public static final int BIND_NOT_FOREGROUND = 0x0004;
public static final int BIND_ABOVE_CLIENT = 0x0008;
public static final int BIND_ALLOW_OOM_MANAGEMENT = 0x0010;
public static final int BIND_WAIVE_PRIORITY = 0x0020;
public static final int BIND_IMPORTANT = 0x0040;
public static final int BIND_ADJUST_WITH_ACTIVITY = 0x0080;
public static final int BIND_VISIBLE = 0x0100;
public static final int BIND_NOT_VISIBLE = 0x40000000;

getSystemService相关

public static final String POWER_SERVICE = "power";
public static final String WINDOW_SERVICE = "window";
public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
public static final String ACCOUNT_SERVICE = "account";
public static final String ACTIVITY_SERVICE = "activity";
public static final String ALARM_SERVICE = "alarm";
public static final String NOTIFICATION_SERVICE = "notification";
public static final String ACCESSIBILITY_SERVICE = "accessibility";
public static final String KEYGUARD_SERVICE = "keyguard";
public static final String LOCATION_SERVICE = "location";
public static final String COUNTRY_DETECTOR = "country_detector";
public static final String SEARCH_SERVICE = "search";
public static final String SENSOR_SERVICE = "sensor";
public static final String STORAGE_SERVICE = "storage";
public static final String WALLPAPER_SERVICE = "wallpaper";
public static final String VIBRATOR_SERVICE = "vibrator";
public static final String STATUS_BAR_SERVICE = "statusbar";
public static final String CONNECTIVITY_SERVICE = "connectivity";
public static final String THROTTLE_SERVICE = "throttle";
public static final String UPDATE_LOCK_SERVICE = "updatelock";
public static final String NETWORKMANAGEMENT_SERVICE = "network_management";
public static final String NETWORK_STATS_SERVICE = "netstats";
public static final String NETWORK_POLICY_SERVICE = "netpolicy";
public static final String WIFI_SERVICE = "wifi";
public static final String WIFI_P2P_SERVICE = "wifip2p";
public static final String NSD_SERVICE = "servicediscovery";
public static final String AUDIO_SERVICE = "audio";
public static final String MEDIA_ROUTER_SERVICE = "media_router";
public static final String TELEPHONY_SERVICE = "phone";
public static final String CLIPBOARD_SERVICE = "clipboard";
public static final String INPUT_METHOD_SERVICE = "input_method";
public static final String TEXT_SERVICES_MANAGER_SERVICE = "textservices";
public static final String APPWIDGET_SERVICE = "appwidget";
public static final String BACKUP_SERVICE = "backup";
public static final String DROPBOX_SERVICE = "dropbox";
public static final String DEVICE_POLICY_SERVICE = "device_policy";
public static final String UI_MODE_SERVICE = "uimode";
public static final String DOWNLOAD_SERVICE = "download";
public static final String NFC_SERVICE = "nfc";
public static final String BLUETOOTH_SERVICE = "bluetooth";
public static final String SIP_SERVICE = "sip";
public static final String USB_SERVICE = "usb";
public static final String SERIAL_SERVICE = "serial";
public static final String INPUT_SERVICE = "input";
public static final String DISPLAY_SERVICE = "display";
public static final String SCHEDULING_POLICY_SERVICE = "scheduling_policy";
public static final String USER_SERVICE = "user";

createPackageContext相关

  • ClassLoader可实例化application,增加application context安全限制
  • 忽略application context安全限制,可随时被加载
  • 带限制的context
public static final int CONTEXT_INCLUDE_CODE = 0x00000001;
public static final int CONTEXT_IGNORE_SECURITY = 0x00000002;
public static final int CONTEXT_RESTRICTED = 0x00000004;

方法

Resources相关

public abstract Resources getResources();

public final CharSequence getText(int resId) {
    return getResources().getText(resId);
}

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

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

context相关

getApplicationContext()获取全局Context,只与当前应用有关,不绑定其他组件

public abstract Context getApplicationContext();

public void registerComponentCallbacks(ComponentCallbacks callback) {
    getApplicationContext().registerComponentCallbacks(callback);
}

public void unregisterComponentCallbacks(ComponentCallbacks callback) {
    getApplicationContext().unregisterComponentCallbacks(callback);
}

根据应用名新生成一个context,与正常启动的context有相同的resources和classloader)

public abstract Context createPackageContext(String packageName,int flags) throws PackageManager.NameNotFoundException;
public abstract Context createPackageContextAsUser(String packageName, int flags, UserHandle user) throws PackageManager.NameNotFoundException;

根据指定Configuration生成一个context,其resources不同

public abstract Context createConfigurationContext(Configuration overrideConfiguration);

根据指定Display生成一个context,其metrics不同

public abstract Context createDisplayContext(Display display);

判断当前context是否被限制

public boolean isRestricted() {
	return false;
}

Theme相关

设置Theme需要在view实例化之前

public abstract void setTheme(int resid);
public abstract Resources.Theme getTheme();

public int getThemeResId() {
    return 0;
}

Attributes相关

返回Resources.Theme的对应函数

public final TypedArray obtainStyledAttributes(int[] attrs) {
    return getTheme().obtainStyledAttributes(attrs);
}

public final TypedArray obtainStyledAttributes(int resid, int[] attrs) throws Resources.NotFoundException {
    return getTheme().obtainStyledAttributes(resid, attrs);
}

public final TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs) {
    return getTheme().obtainStyledAttributes(set, attrs, 0, 0);
}
public final TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) {
    return getTheme().obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes);
}

Package相关

获取PackageManager、包名、资源文件中的路径、代码中的路径

public abstract PackageManager getPackageManager();
public abstract String getPackageName();
public abstract String getPackageResourcePath();
public abstract String getPackageCodePath();

SharedPreferences相关

获取SharedPreferences和对应文件

public abstract File getSharedPrefsFile(String name);
public abstract SharedPreferences getSharedPreferences(String name, int mode);

I/O相关

获取I/O流、删除文件、根据name获取File、获取openFileOutput()方法存放目录、获取外部设备File的存放目录、获取Obb文件的存放目录、获取Cache目录、获取外部设备Cache目录、获取应用所有文件名、获取openFileOutput()方法存放目录中的目录

public abstract FileInputStream openFileInput(String name) throws FileNotFoundException;
public abstract FileOutputStream openFileOutput(String name, int mode)throws FileNotFoundException;
public abstract boolean deleteFile(String name);
public abstract File getFileStreamPath(String name);
public abstract File getFilesDir();
public abstract File getExternalFilesDir(String type);
public abstract File getObbDir();
public abstract File getCacheDir();
public abstract File getExternalCacheDir();
public abstract String[] fileList();
public abstract File getDir(String name, int mode);

数据库相关

创建或打开已有数据库、删除数据库、获取数据库路径、获取应用所有数据库名

public abstract SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory);
public abstract SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler);
public abstract boolean deleteDatabase(String name);
public abstract File getDatabasePath(String name);
public abstract String[] databaseList();

Wallpaper相关

下列方法都被WallpaperManager所取代

public abstract Drawable getWallpaper();
public abstract Drawable peekWallpaper();
public abstract int getWallpaperDesiredMinimumWidth();
public abstract int getWallpaperDesiredMinimumHeight();
public abstract void setWallpaper(Bitmap bitmap) throws IOException;
public abstract void setWallpaper(InputStream data) throws IOException;
public abstract void clearWallpaper() throws IOException;

Activity相关

启动Activity、通过指定User启动(预装应用使用),启动一群Activity(实际只会先创建栈顶的,其余的在访问时才会创建)

public abstract void startActivity(Intent intent);
public void startActivityAsUser(Intent intent, UserHandle user) {
    throw new RuntimeException("Not implemented. Must override in a subclass.");
}
 
public abstract void startActivity(Intent intent, Bundle options);
public void startActivityAsUser(Intent intent, Bundle options, UserHandle userId) {
    throw new RuntimeException("Not implemented. Must override in a subclass.");
}

public abstract void startActivities(Intent[] intents);
public abstract void startActivities(Intent[] intents, Bundle options);
public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) {
    throw new RuntimeException("Not implemented. Must override in a subclass.");
}

options为启动方式,如:当Activity由非Activity启动时,需加上FLAG_ACTIVITY_NEW_TASK,因为当前没有任务栈,需重新创建一个

IntentSender相关

public abstract void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException;
public abstract void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException;

Broadcast相关

sendBroadcast是异步的,发送的广播不能传递,不能被中断,参数receiverPermission表示需要指定权限的Receiver才能接收广播

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

sendOrderedBroadcast发送的广播可传递,可被中断,参数resultReceiver为指定的接收者

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);

StickyBroadcast,该广播会持续存在或者多次发送

public abstract void sendStickyBroadcast(Intent intent);
public abstract void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras);
public abstract void removeStickyBroadcast(Intent intent);

通过指定User启动(预装应用使用)

public abstract void sendBroadcastAsUser(Intent intent, UserHandle user);
public abstract void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission);
public abstract void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras);
public abstract void sendStickyBroadcastAsUser(Intent intent, UserHandle user);
public abstract void removeStickyBroadcastAsUser(Intent intent, UserHandle user);

注册广播接收者

  • 如有多个action匹配,只会返回第一个action对应的事件,其他的action由系统响应
  • Android 14之后要调用setPackage指定接收应用包名
  • 不可在BroadcastReceiver中调用,否则会让两者生命周期绑定
  • broadcastPermission指定权限,scheduler指定可接收广播的线程(默认主线程)
public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter);
public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler);
public abstract Intent registerReceiverAsUser(BroadcastReceiver receiver,UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler);
public abstract void unregisterReceiver(BroadcastReceiver receiver);

Service相关

startService开启的服务常驻后台,stopService时若还有绑定则不会销毁

public abstract ComponentName startService(Intent service);
public abstract boolean stopService(Intent service);
public abstract ComponentName startServiceAsUser(Intent service, UserHandle user);
public abstract boolean stopServiceAsUser(Intent service, UserHandle user);

bindService开启的服务与调用的context有关

  • 不可在BroadcastReceiver中调用,否则会让两者生命周期绑定
public abstract boolean bindService(Intent service, ServiceConnection conn, int flags);
public boolean bindService(Intent service, ServiceConnection conn, int flags, int userHandle) {
    throw new RuntimeException("Not implemented. Must override in a subclass.");
}
public abstract void unbindService(ServiceConnection conn);

Permission相关

  • 查询/赋予指定pid或uid权限
  • 查询/赋予当前调用者权限(需在IPC中,否则fail)
  • 查询/赋予当前调用者权限(如不在IPC,则赋予权限)
public abstract int checkPermission(String permission, int pid, int uid);
public abstract int checkCallingPermission(String permission);
public abstract int checkCallingOrSelfPermission(String permission);
public abstract void enforcePermission(String permission, int pid, int uid, String message);
public abstract void enforceCallingPermission(String permission, String message);
public abstract void enforceCallingOrSelfPermission(String permission, String message);

UriPermission相关

  • 授予Package 访问Content Provider Uri的权限
  • 撤销Uri下所有的权限
public abstract void grantUriPermission(String toPackage, Uri uri, int modeFlags);
public abstract void revokeUriPermission(Uri uri, int modeFlags);
  • 查询/赋予Pid或uid是否有Uri权限
  • 查询/赋予当前调用者权限(需在IPC中,否则fail)
  • 查询/赋予当前调用者权限(如不在IPC,则赋予权限)
  • 同时查询Permission和UriPermission
public abstract int checkUriPermission(Uri uri, int pid, int uid, int modeFlags);
public abstract int checkCallingUriPermission(Uri uri, int modeFlags);
public abstract int checkCallingOrSelfUriPermission(Uri uri, int modeFlags);
public abstract void enforceUriPermission(Uri uri, int pid, int uid, int modeFlags, String message);
public abstract void enforceCallingUriPermission(Uri uri, int modeFlags, String message);
public abstract void enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message);

public abstract int checkUriPermission(Uri uri, String readPermission,String writePermission, int pid, int uid, int modeFlags);

其他

public abstract AssetManager getAssets();
public abstract ContentResolver getContentResolver();
public abstract Looper getMainLooper();
public abstract ClassLoader getClassLoader();
public abstract ApplicationInfo getApplicationInfo();
public abstract boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments);
public abstract Object getSystemService(String name);
public abstract CompatibilityInfoHolder getCompatibilityInfo(int displayId);

ContextWrapper

ContextWrapper是Context的代理类,内部维护一个Context域,并调用其对应方法(重复的不再赘述)

public class ContextWrapper extends Context {
    Context mBase;

    public ContextWrapper(Context base) {
        mBase = base;
    }
    
    protected void attachBaseContext(Context base) {
        if (mBase != null) {
            throw new IllegalStateException("Base context already set");
        }
        mBase = base;
    }
    public Context getBaseContext() {
        return mBase;
    }
}

你可能感兴趣的:(#,Android源码,android,java,开发语言)