Context类简单解析

Context上下文对象

通过它可以获取应用整体信息的接口:

直接实现类

ContextWrapper  
MockContext

间接实现类:

ContextThemeWrapper  acticity就是集成这个类 所有activity里面获取相关资源的api全部从这个地方来的

常用api

Context类简单介绍
1:提供创建文件的模式  eg:public static final int MODE_PRIVATE = 0x0000;
2:提供bindService的相关模式  public static final int BIND_AUTO_CREATE = 0x0001;
3:获取sharepreferense存储数据  getSharedPreferences
4:数据库操作api
5:getAssets()
6:getResources();
7:getPackageManager()
8:getContentResolver()
9:getMainLooper()
10:getApplicationContext()
11: public final CharSequence getText(@StringRes int resId) {
        return getResources().getText(resId);
    }
12:public final int getColor(int id) {
        return getResources().getColor(id, getTheme());
    }
13:public final Drawable getDrawable(int id) {
        return getResources().getDrawable(id, getTheme());
    }
14:public final ColorStateList getColorStateList(int id) {
        return getResources().getColorStateList(id, getTheme());
    }
15:public abstract void setTheme(@StyleRes int resid);
16:public final TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
        return getTheme().obtainStyledAttributes(attrs);
    }
17:public final TypedArray obtainStyledAttributes(
            @StyleRes int resid, @StyleableRes int[] attrs) throws Resources.NotFoundException {
        return getTheme().obtainStyledAttributes(resid, attrs);
    }
18:public final TypedArray obtainStyledAttributes(
            AttributeSet set, @StyleableRes int[] attrs) {
        return getTheme().obtainStyledAttributes(set, attrs, 0, 0);
    }
19:public abstract ClassLoader getClassLoader();
20:public abstract String getPackageName();
    public abstract String getBasePackageName();

21:public abstract ApplicationInfo getApplicationInfo();
22:public abstract String getPackageResourcePath();
23:public abstract String getPackageCodePath();
24:public abstract File getSharedPrefsFile(String name);
25:public abstract SharedPreferences getSharedPreferences(String name,
            int mode);
26:/**
     * Open a private file associated with this Context's application package
     * for reading.
     *
     * @param name The name of the file to open; can not contain path
     *             separators.
     *
     * @return The resulting {@link FileInputStream}.
     *
     * @see #openFileOutput
     * @see #fileList
     * @see #deleteFile
     * @see java.io.FileInputStream#FileInputStream(String)
     */
    public abstract FileInputStream openFileInput(String name)
        throws FileNotFoundException;
27:/**
     * Open a private file associated with this Context's application package
     * for writing.  Creates the file if it doesn't already exist.
     *
     * <p>No permissions are required to invoke this method, since it uses internal
     * storage.
     *
     * @param name The name of the file to open; can not contain path
     *             separators.
     * @param mode Operating mode.  Use 0 or {@link #MODE_PRIVATE} for the
     * default operation, {@link #MODE_APPEND} to append to an existing file,
     * {@link #MODE_WORLD_READABLE} and {@link #MODE_WORLD_WRITEABLE} to control
     * permissions.
     *
     * @return The resulting {@link FileOutputStream}.
     *
     * @see #MODE_APPEND
     * @see #MODE_PRIVATE
     * @see #MODE_WORLD_READABLE
     * @see #MODE_WORLD_WRITEABLE
     * @see #openFileInput
     * @see #fileList
     * @see #deleteFile
     * @see java.io.FileOutputStream#FileOutputStream(String)
     */
    public abstract FileOutputStream openFileOutput(String name, int mode)
        throws FileNotFoundException;

28:/**
     * Delete the given private file associated with this Context's
     * application package.
     *
     * @param name The name of the file to delete; can not contain path
     *             separators.
     *
     * @return {@code true} if the file was successfully deleted; else
     *         {@code false}.
     *
     * @see #openFileInput
     * @see #openFileOutput
     * @see #fileList
     * @see java.io.File#delete()
     */
    public abstract boolean deleteFile(String name);
29:public abstract File getFileStreamPath(String name);
30:/**
     * Returns the absolute path to the directory on the filesystem where
     * files created with {@link #openFileOutput} are stored.
     *
     * <p>No permissions are required to read or write to the returned path, since this
     * path is internal storage.
     *
     * @return The path of the directory holding application files.
     *
     * @see #openFileOutput
     * @see #getFileStreamPath
     * @see #getDir
     */
    public abstract File getFilesDir();
31:/**
     * Returns the absolute path to the directory on the primary external filesystem
     * (that is somewhere on {@link android.os.Environment#getExternalStorageDirectory()
     * Environment.getExternalStorageDirectory()}) where the application can
     * place persistent files it owns.  These files are internal to the
     * applications, and not typically visible to the user as media.
     *
     * <p>This is like {@link #getFilesDir()} in that these
     * files will be deleted when the application is uninstalled, however there
     * are some important differences:
     *
     * <ul>
     * <li>External files are not always available: they will disappear if the
     * user mounts the external storage on a computer or removes it.  See the
     * APIs on {@link android.os.Environment} for information in the storage state.
     * <li>There is no security enforced with these files.  For example, any application
     * holding {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} can write to
     * these files.
     * </ul>
     *
     * <p>Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
     * are required to read or write to the returned path; it's always
     * accessible to the calling app.  This only applies to paths generated for
     * package name of the calling application.  To access paths belonging
     * to other packages, {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE}
     * and/or {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} are required.
     *
     * <p>On devices with multiple users (as described by {@link UserManager}),
     * each user has their own isolated external storage. Applications only
     * have access to the external storage for the user they're running as.</p>
     *
     * <p>Here is an example of typical code to manipulate a file in
     * an application's private storage:</p>
     *
     * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
     * private_file}
     *
     * <p>If you supply a non-null <var>type</var> to this function, the returned
     * file will be a path to a sub-directory of the given type.  Though these files
     * are not automatically scanned by the media scanner, you can explicitly
     * add them to the media database with
     * {@link android.media.MediaScannerConnection#scanFile(Context, String[], String[],
     *      android.media.MediaScannerConnection.OnScanCompletedListener)
     *      MediaScannerConnection.scanFile}.
     * Note that this is not the same as
     * {@link android.os.Environment#getExternalStoragePublicDirectory
     * Environment.getExternalStoragePublicDirectory()}, which provides
     * directories of media shared by all applications.  The
     * directories returned here are
     * owned by the application, and their contents will be removed when the
     * application is uninstalled.  Unlike
     * {@link android.os.Environment#getExternalStoragePublicDirectory
     * Environment.getExternalStoragePublicDirectory()}, the directory
     * returned here will be automatically created for you.
     *
     * <p>Here is an example of typical code to manipulate a picture in
     * an application's private storage and add it to the media database:</p>
     *
     * {@sample development/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.java
     * private_picture}
     *
     * @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}.
     *
     * @return The path of the directory holding application files
     * on external storage.  Returns null if external storage is not currently
     * mounted so it could not ensure the path exists; you will need to call
     * this method again when it is available.
     *
     * @see #getFilesDir
     * @see android.os.Environment#getExternalStoragePublicDirectory
     */
    @Nullable
    public abstract File getExternalFilesDir(@Nullable String type);
32:public abstract File[] getExternalFilesDirs(String type);
33:public abstract File getCacheDir();
34:@Nullable
    public abstract File getExternalCacheDir();
35:public abstract File[] getExternalCacheDirs();
36:public abstract SQLiteDatabase openOrCreateDatabase(String name,
            int mode, CursorFactory factory);
37:public abstract boolean deleteDatabase(String name);
38:public abstract File getDatabasePath(String name);
39:@Deprecated
    public abstract Drawable getWallpaper();
40: @Deprecated
    public abstract void setWallpaper(Bitmap bitmap) throws IOException;
41:public abstract void startActivity(Intent intent);
42:public abstract void sendBroadcast(Intent intent);
43:public abstract void sendBroadcast(Intent intent,
            @Nullable String receiverPermission);
44:@SystemApi
    public abstract void sendBroadcast(Intent intent,
            @Nullable String receiverPermission,
            @Nullable Bundle options);
45:public abstract void sendOrderedBroadcast(Intent intent,
            @Nullable String receiverPermission);
    还有其他同构方法
46:@Deprecated
    public abstract void sendStickyBroadcast(Intent intent);

    @Deprecated
    public abstract void sendStickyOrderedBroadcast(Intent intent,
            BroadcastReceiver resultReceiver,
            @Nullable Handler scheduler, int initialCode, @Nullable String initialData,
            @Nullable Bundle initialExtras);
    @Deprecated
    public abstract void removeStickyBroadcast(Intent intent);
47:@Nullable
    public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver,
                                            IntentFilter filter);
    @Nullable
    public abstract Intent registerReceiver(BroadcastReceiver receiver,
            IntentFilter filter, @Nullable String broadcastPermission,
            @Nullable Handler scheduler);
    public abstract void unregisterReceiver(BroadcastReceiver receiver);
48:@Nullable
    public abstract ComponentName startService(Intent service);
    public abstract boolean stopService(Intent service);
    public abstract boolean bindService(Intent service, @NonNull ServiceConnection conn,
            @BindServiceFlags int flags);
    public abstract void unbindService(@NonNull ServiceConnection conn);
49:public abstract Object getSystemService(@ServiceName @NonNull String name);
    public static final String POWER_SERVICE = "power";
    各类service的名称都在Context类里面以静态常量的形式存在
50:@CheckResult(suggest="#enforcePermission(String,int,int,String)")
    @PackageManager.PermissionResult
    public abstract int checkPermission(@NonNull String permission, int pid, int uid);

    /** @hide */
    @PackageManager.PermissionResult
    public abstract int checkPermission(@NonNull String permission, int pid, int uid,
            IBinder callerToken);

    @CheckResult(suggest="#enforceCallingPermission(String,String)")
    @PackageManager.PermissionResult
    public abstract int checkCallingPermission(@NonNull String permission);

    @PackageManager.PermissionResult
    public abstract int checkSelfPermission(@NonNull String permission);

    public abstract void enforcePermission(
            @NonNull String permission, int pid, int uid, @Nullable String message);

    public abstract void grantUriPermission(String toPackage, Uri uri,
            @Intent.GrantUriMode int modeFlags);

    @CheckResult(suggest="#enforceUriPermission(Uri,int,int,String)")
    public abstract int checkUriPermission(Uri uri, int pid, int uid,
            @Intent.AccessUriMode int modeFlags);

51:public abstract int getUserId();








  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值