`
jacky-zhang
  • 浏览: 316656 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

getSharedPreferences(String name, int mode) of Service的实现(转)

阅读更多
I found a method getSharedPreferences(String name, int mode) in Service class

than I want to see how it implements

first I got a abstrat method in Context class

/android_opensource/frameworks/base/core/java/android/content/Context.java
...
262     /**
263      * Retrieve and hold the contents of the preferences file 'name', returning
264      * a SharedPreferences through which you can retrieve and modify its
265      * values.  Only one instance of the SharedPreferences object is returned
266      * to any callers for the same name, meaning they will see each other's
267      * edits as soon as they are made.
268      *
269      * @param name Desired preferences file. If a preferences file by this name
270      * does not exist, it will be created when you retrieve an
271      * editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
272      * @param mode Operating mode.  Use 0 or {@link #MODE_PRIVATE} for the
273      * default operation, {@link #MODE_WORLD_READABLE}
274      * and {@link #MODE_WORLD_WRITEABLE} to control permissions.
275      *
276      * @return Returns the single SharedPreferences instance that can be used
277      *         to retrieve and modify the preference values.
278      *
279      * @see #MODE_PRIVATE
280      * @see #MODE_WORLD_READABLE
281      * @see #MODE_WORLD_WRITEABLE
282      */
283     public abstract SharedPreferences getSharedPreferences(String name,
284             int mode);
...


and Service extends ContextWrapper, ContextWrapper extends Context just implements from a new Context instance
/android_opensource/frameworks/base/core/java/android/content/ContextWrapper.java
...
132     @Override
133     public SharedPreferences getSharedPreferences(String name, int mode) {
134         return mBase.getSharedPreferences(name, mode);
135     }
...


so where does it pass the Context instance to the Service

The Context instance must implements the method

than I found the implementation in ApplicationContext which extends the Context

android_opensource/frameworks/base/core/java/android/app/ApplicationContext.java
...
@Override
303     public SharedPreferences getSharedPreferences(String name, int mode) {
304         SharedPreferencesImpl sp;
305         File f = makeFilename(getPreferencesDir(), name + ".xml");
306         synchronized (sSharedPrefs) {
307             sp = sSharedPrefs.get(f);
308             if (sp != null && !sp.hasFileChanged()) {
309                 //Log.i(TAG, "Returning existing prefs " + name + ": " + sp);
310                 return sp;
311             }
312         }
313
314         FileInputStream str = null;
315         File backup = makeBackupFile(f);
316         if (backup.exists()) {
317             f.delete();
318             backup.renameTo(f);
319         }
320
321         // Debugging
322         if (f.exists() && !f.canRead()) {
323             Log.w(TAG, "Attempt to read preferences file " + f + " without permission");
324         }
325
326         Map map = null;
327         if (f.exists() && f.canRead()) {
328             try {
329                 str = new FileInputStream(f);
330                 map = XmlUtils.readMapXml(str);
331                 str.close();
332             } catch (org.xmlpull.v1.XmlPullParserException e) {
333                 Log.w(TAG, "getSharedPreferences", e);
334             } catch (FileNotFoundException e) {
335                 Log.w(TAG, "getSharedPreferences", e);
336             } catch (IOException e) {
337                 Log.w(TAG, "getSharedPreferences", e);
338             }
339         }
340
341         synchronized (sSharedPrefs) {
342             if (sp != null) {
343                 //Log.i(TAG, "Updating existing prefs " + name + " " + sp + ": " + map);
344                 sp.replace(map);
345             } else {
346                 sp = sSharedPrefs.get(f);
347                 if (sp == null) {
348                     sp = new SharedPreferencesImpl(f, mode, map);
349                     sSharedPrefs.put(f, sp);
350                 }
351             }
352             return sp;
353         }
354     }
...


but I still did't found where it pass the ApplicationContext in

after few minutes search I found another class ActivityThread

It had a method handleCreateService which should be called when create a Service

android_opensource/frameworks/base/core/java/android/app/ActivityThread.java
...
2436     private final void handleCreateService(CreateServiceData data) {
2437         // If we are getting ready to gc after going to the background, well
2438         // we are back active so skip it.
2439         unscheduleGcIdler();
2440
2441         PackageInfo packageInfo = getPackageInfoNoCheck(
2442                 data.info.applicationInfo);
2443         Service service = null;
2444         try {
2445             java.lang.ClassLoader cl = packageInfo.getClassLoader();
2446             service = (Service) cl.loadClass(data.info.name).newInstance();
2447         } catch (Exception e) {
2448             if (!mInstrumentation.onException(service, e)) {
2449                 throw new RuntimeException(
2450                     "Unable to instantiate service " + data.info.name
2451                     + ": " + e.toString(), e);
2452             }
2453         }
2454
2455         try {
2456             if (localLOGV) Log.v(TAG, "Creating service " + data.info.name);
2457
2458             ApplicationContext context = new ApplicationContext();
2459             context.init(packageInfo, null, this);
2460
2461             Application app = packageInfo.makeApplication();
2462             context.setOuterContext(service);
2463             service.attach(context, this, data.info.name, data.token, app,
2464                     ActivityManagerNative.getDefault());
2465             service.onCreate();
2466             mServices.put(data.token, service);
2467             try {
2468                 ActivityManagerNative.getDefault().serviceDoneExecuting(data.token);
2469             } catch (RemoteException e) {
2470                 // nothing to do.
2471             }
2472         } catch (Exception e) {
2473             if (!mInstrumentation.onException(service, e)) {
2474                 throw new RuntimeException(
2475                     "Unable to create service " + data.info.name
2476                     + ": " + e.toString(), e);
2477             }
2478         }
2479     }
...


In the method it call the service's method attch and pass a ApplicationContext as parameter

then The service's attch method would pass the context throght the attachBaseContext(context) method
android_opensource/frameworks/base/core/java/android/app/Service.java
...
356     public final void attach(
357             Context context,
358             ActivityThread thread, String className, IBinder token,
359             Application application, Object activityManager) {
360         attachBaseContext(context);
361         mThread = thread;           // NOTE:  unused - remove?
362         mClassName = className;
363         mToken = token;
364         mApplication = application;
365         mActivityManager = (IActivityManager)activityManager;
366     }
...

android_opensource/frameworks/base/core/java/android/content/ContextWrapper.java
...
50     /**
51      * Set the base context for this ContextWrapper.  All calls will then be
52      * delegated to the base context.  Throws
53      * IllegalStateException if a base context has already been set.
54      *
55      * @param base The new base context for this wrapper.
56      */
57     protected void attachBaseContext(Context base) {
58         if (mBase != null) {
59             throw new IllegalStateException("Base context already set");
60         }
61         mBase = base;
62     }
...

so the service get the Context instance which implement the getSharedPreferences(String name, int mode) method

the original url http://hi.baidu.com/ksoftware/blog/item/de17bbd6806b202507088bd8.html
分享到:
评论

相关推荐

    09 数据存储(一)1

    SharedPreferences提供了简单易用的API,开发者可以通过`Context`的`getSharedPreferences(String name, int mode)`方法获取一个SharedPreferences实例,其中`name`参数是SharedPreferences文件的名称,而`mode`参数...

    SharedPreferences工具类

    - `getSharedPreferences(String name, int mode)`: 全局的SharedPreferences,根据指定名称和模式创建实例。 - `getPreferences(int mode)`: 当前Activity的SharedPreferences,使用当前类名作为默认名称。 - *...

    Android总结

    - 调用 `getSharedPreferences(String name, int mode)` 方法获取 `SharedPreferences` 对象。 - 使用 `edit()` 方法获取 `Editor` 对象,通过调用 `putXXX(key, value)` 方法写入数据。 - 最后调用 `apply()` 或...

    android ini文件 sharePrefernces 保存数据

    - `Activity.getSharedPreferences(String name, int mode)`:在当前`Activity`上下文中获取偏好设置,仅限于当前`Activity`。 其中,`name`参数是偏好设置文件的名称,`mode`参数表示访问模式,例如`MODE_PRIVATE`...

    SharedPreferences存储

    - `getSharedPreferences(String name, int mode)`:在任何类中使用,需要传入首选项的名称和模式。 2. **编辑SharedPreferences** - `SharedPreferences.Editor`:通过`edit()`方法获取,用于添加、修改或删除...

    数据存储之Preferences

    1. 使用方式:SharedPreferences通过Context对象获取,如`getSharedPreferences(String name, int mode)`,其中name是SharedPreferences文件的名称,mode是访问模式,如MODE_PRIVATE(默认)表示私有模式,只有当前...

    SharedPreferences的使用

    - `getSharedPreferences(String name, int mode)`:这个方法在`Context`中定义,传入文件名和访问模式(如私有模式、只读模式等)来创建SharedPreferences对象。 - `Activity.getPreferences(int mode)`:针对...

    Android开发SharedPreferences使用及调用文件管理器自定义读取文件实现

    1. **创建SharedPreferences对象**:通常在应用的Context环境下,如Activity或Service中,通过`getSharedPreferences(String name, int mode)`方法创建一个SharedPreferences对象,其中`name`参数是文件名,`mode`...

    SharedPreferences

    - `getSharedPreferences(String name, int mode)`: 这个静态方法是通过Context对象来获取SharedPreferences实例。`name`参数用于指定SharedPreferences文件的名称,通常默认为“preferences”。`mode`参数定义了...

    Android 使用SharedPreferences实现数据的读写

    - `getSharedPreferences(String name, int mode)`:适用于全局偏好设置,需要传入文件名(默认为`PreferenceManager.getDefaultSharedPreferences(Context context)`)和访问模式(如`Context.MODE_PRIVATE`)。...

    Android数据操作工具类

    1. **获取SharedPreferences实例**:通常会提供一个静态方法,用于获取SharedPreferences的实例,例如`getSharedPreferences(String name, int mode)`,其中name是文件名,mode是访问模式。 2. **保存键值对**:...

    SharedPreferences详解

    它支持多种基本数据类型的存储,如boolean、int、float、long和String等。 获取SharedPreferences对象有两种主要方式: 1. 使用Context对象的getSharedPreferences()方法,传入一个文件名(作为SharedPreferences...

    SharedPreferences基本使用

    - 获取SharedPreferences对象:通常在Activity或Fragment中,通过`getPreferences(MODE_PRIVATE)`方法获取当前组件的SharedPreferences,或者通过`getSharedPreferences(String name, int mode)`方法传入自定义的...

    Android应用源码之SharedPreferences.zip

    - `getSharedPreferences(String name, int mode)`:这是获取SharedPreferences实例的方法,`name`是配置文件的名称,`mode`是访问模式,如私有(Context.MODE_PRIVATE)。 - `edit()`:返回一个`...

    android的SharedPreferences用法举例源代码

    - `getSharedPreferences(String name, int mode)`:通过传入文件名和访问模式来获取,例如`getSharedPreferences("my_prefs", Context.MODE_PRIVATE)`,其中"my_prefs"是文件名,`Context.MODE_PRIVATE`表示私有...

    sharedPreferences

    1. `getSharedPreferences(String name, int mode)`:这个静态方法用于获取一个`SharedPreferences`实例。`name`参数定义了首选项文件的名称,`mode`参数则定义了访问模式,比如只读或读写。 2. `edit()`:此方法...

    Android源码——登录界面记住密码功能源码_new_61.zip

    - 创建 SharedPreferences 实例:通过 `getSharedPreferences(String name, int mode)` 方法,其中 `name` 是首选项文件的名称,`mode` 决定了文件的访问权限。 - 存储数据:使用 `edit()` 方法获取到 `...

    SharedPreferences源码解析及应用.docx

    }// ContextImpl.java@Overridepublic SharedPreferences getSharedPreferences(String name, int mode) { synchronized (mSync) { SharedPreferencesImpl sp = mPreferencesMap.get(name); if (sp == null) { File ...

    疯狂android资料:第八章android的数据存储和IO.doc

    注意,SharedPreferences实例需要通过`Context`的`getSharedPreferences(String name, int mode)`方法获取,其中`mode`参数决定了数据的读写权限。 关于SharedPreferences的存储位置,它们通常位于应用的私有数据...

    安卓Android源码——sharedPref1.rar

    - `getSharedPreferences(String name, int mode)`: 根据给定的名字和访问模式创建或获取`SharedPreferences`对象。 - `getString(String key, String defValue)`: 获取存储的字符串值。 - `putString(String key...

Global site tag (gtag.js) - Google Analytics