`
jacky-zhang
  • 浏览: 309938 次
  • 性别: 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
分享到:
评论

相关推荐

    Android程序技术:个人学习助手项目注册功能的实现.pptx

    value值只能是float、int、long、boolean、String、StringSet类型数据。 SharedPreferences的特点 SharedPreferences的特点 存储数据 SharedPreferences的使用 The use of the SharedPreferences SharedPreferences...

    SharedPrefsUtil.java App存储数据工具类

    public static int getIntValue(Context context, String key, int defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); int value = sp.getInt(key, ...

    实验10-Android数据存储和IO.doc

    调用App1的Context的getSharedPreferences(String name,int mode) 即可获取相应的SharedPreferences对象。 如果需要向App1的SharedPreferences数据写入数据,调用SharedPreferences的e dit()方法获取相应的Editor...

    Android SharedPreferences实现记住密码和自动登录界面

    SharedPreferences介绍: SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置参数,它是采用xml文件存放数据的,文件存放在”/data/data...Context.getSharedPreferences(String name

    Android数据共享 sharedPreferences 的使用方法

    context.getSharedPreferences(name, Context.MODE_PRIVATE); 设置要保存的数据: mSp = context.getSharedPreferences(name, Context.MODE_PRIVATE); mEditor = mSp.edit(); mEditor.putString(test, ab

     Android的SharedPreferences的使用

    SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。比较经典的使用方式例如用户输入框对过往登录账户的存储。 详细介绍请参考博文:...

    kotlin-shared-preferences

    共享首选项用于访问和修改Context.getSharedPreferences(String,int)返回的首选项数据的接口。 对于任何特定的首选项集,所有客户端都共享一个此类的单个实例。 对首选项的修改必须经过一个Editor对象,以确保首...

    Android SharedPreferences存储的正确写法

    SharedPreferences 特点 即便是Android小白都知道的SharedPreferences的用法,这是保存数据最简便的方法,但是不处理好的话后期维护将是一个巨大...SharedPreferences的具体实现并不在公开API内,创建方法只有通过Cont

    Android轻松实现多语言的方法示例

    本文介绍了Android轻松实现多语言的方法示例,分享给大家,具体如下: 1.创建多语言包 2.首先在onCreate方法中调用此方法... SharedPreferences sharedPreferences = getSharedPreferences(key, MODE_PRIVATE); i

    保存用户名密码

    保存用户名密码小实例 SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);

    android中SharedPreferences实现存储用户名功能

    1. 简介 SharedPreferences是一种轻型...接收两个参数,第一个参数指定存储数据的文件,若指定文件不存在,则新建该文件,存放目录为”/data/data/package_name/shared_prefs/”,其中package_name为包名。 第二个参数

    ligin_日记本.zip

    SharedPreferences sp = this.getSharedPreferences("pwd", Context.MODE_PRIVATE);

    SharedPreferences实例

    android SharedPreferences实例

    SharePreferences:SharePreferences存储

    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit(); editor.putString("name", "Tom"); editor.putBoolean("married", false); editor.apply(); 小Tips TextUtils....

    android判断软件是否第一次运行的方法

    SharedPreferences sharedPreferences = this.getSharedPreferences(share, MODE_PRIVATE); boolean isFirstRun = sharedPreferences.getBoolean(isFirstRun, true); Editor editor = sharedPreferences.edit(); if ...

    Android SharedPreferences的使用分析

    代码如下: public void savePreferences(String name, Integer age) {–>> get SharedPreferences SharedPreferences preferences = context.getSharedPreferences(“itcase”,Context.MODE_PRIVATE); // 不需要...

    Android中使用SharedPreferences完成记住账号密码的功能

    效果图: ... 分析: SharedPreferences可将数据存储到本地的配置文件中 ... SharedPreferences使用方法: 1、创建名为config的配置文件...config=getSharedPreferences(config, MODE_PRIVATE); 2、添加编辑器 Editor edit

    SharedPreferences记住密码

    SharedPreferences sp = getSharedPreferences("bh", MODE_PRIVATE); Editor editor = sp.edit();//编辑器 editor.putString("username", username.getText().toString()); editor.putString("userpwd", userpwd....

    Android Studio sharePreferences 存取键值对示例

    分别使用getPreferences()和getSharedPreferences()建立xml文件,UI上输入数据类型、键、值之后点击保存即可。 可以使用adb查看data/data/<package-name>/shared_prefs/路径下生成的xml,也可以通过输入键名点击Read...

    详解Android四种存储方式

    在Android程序开发中我们经常遇到...SharedPreferences.Editor sharedata = getSharedPreferences(data, 0).edit(); sharedata.putString(name,shenrenkui); sharedata.commit(); 在B中取值: SharedPreferences sha

Global site tag (gtag.js) - Google Analytics