Android-SharedPreferences共享级别(单个activity,同一package下,application之间)

本文介绍Android中SharedPreferences的基本使用方法,包括如何获取、保存及读取数据。同时提供了完整的示例代码,展示如何通过SharedPreferences存储和读取字符串数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,是ANDROID源代码如下:

public abstract SharedPreferences getSharedPreferences (String name,int mode)
Since:   APILevel 1

Retrieve and hold the contents of the preferences file 'name',returning a SharedPreferences through which you can retrieve andmodify its values. Only one instance of the SharedPreferencesobject is returned to any callers for the same name, meaning theywill see each other's edits as soon as they are made.

Parameters
name Desired preferences file. If a preferences file by this name doesnot exist, it will be created when you retrieve an editor(SharedPreferences.edit()) and then commit changes(Editor.commit()).
mode Operating mode. Use 0 or MODE_PRIVATE forthe default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE tocontrol permissions. The bit MODE_MULTI_PROCESS canalso be used if multiple processes are mutating the sameSharedPreferences file.MODE_MULTI_PROCESS isalways on in apps targetting Gingerbread (Android 2.3) and below,and off by default in later versions.
Returns
  • Returns the single SharedPreferences instance that can be used toretrieve and modify the preference values.



SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);通过名称,得到一个SharedPreferences,这个Preferences 是共享的,共享的范围据现在同一个Package中

这里面说所的Package和Java里面的那个Package不同,貌似这里面的Package是指在AndroidManifest.xml文件中:

<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.roiding.sample.note"
android:versionCode="1"
android:versionName="1.0.0">


而于一个Activity中调用  public SharedPreferences getPreferences (intmode)  方法,则是Activity级别的。


详解:


很多时候我们开发的软件需要保存一些用户设置的信息,例如是否记住密码、显示的字体大小等等。如果是window软件通常我们会采用ini文件进行保存,如果是j2se应用,我们会采用properties属性文件进行保存。

在Android国度里,我们使用SharedPreferences是最合适不过的了,SharedPreferences是一个轻量级的存储类,特别适合用于保存软件配置参数。SharedPreferences其背后是用xml文件存放数据,文件存放在/data/data/packagename/shared_prefs目录下。

下面我写了一个SharedPreferences_Demo,需要的同志可以Download下来看看。欢迎交流学习。

首先,我写了一个工具类,用来进行SharedPreferences的相关操作:

 

Java代码   收藏代码
  1. package com.iteye.dengwho;  
  2.   
  3. import android.content.Context;  
  4. import android.content.SharedPreferences;  
  5. import android.content.SharedPreferences.Editor;  
  6.   
  7. public class SharedPreferencesUtil  
  8.     private SharedPreferences sp;  
  9.     private Editor editor;  
  10.     private final static String SP_NAME "mydata" 
  11.     private final static int MODE Context.MODE_WORLD_READABLE  
  12.             Context.MODE_WORLD_WRITEABLE;  
  13.   
  14.     public SharedPreferencesUtil(Context context)  
  15.         sp context.getSharedPreferences(SP_NAME, MODE);  
  16.         editor sp.edit();  
  17.      
  18.   
  19.     public boolean save(String key, String value)  
  20.         editor.putString(key, value);  
  21.         // 亿万不要忘了加commit呐~~~!!!!  
  22.         return editor.commit();  
  23.      
  24.   
  25.     public String read(String key)  
  26.         String str null 
  27.         str sp.getString(key, null);  
  28.         return str;  
  29.      
  30.  

 

这里我用我的血泪屎来提醒大家在save的操作时1000万不要忘了commit()。
另外,因为SharedPreferences本身就是以XML保存文件的,所以我们不用给它命名时多加“.xml”后缀。

下面是Activity类:

 

Java代码   收藏代码
  1. package com.iteye.dengwho;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. import android.widget.EditText;  
  9. import android.widget.Toast;  
  10.   
  11. public class SharedPreferenced_DemoActivity extends Activity  
  12.     private Button saveBtn;  
  13.     private Button readBtn;  
  14.     private EditText inputEv;  
  15.     private EditText showEv;  
  16.     private SharedPreferencesUtil util;  
  17.   
  18.       
  19.     public void init()  
  20.         util new SharedPreferencesUtil(this);  
  21.         saveBtn (Button) findViewById(R.id.save_btn);  
  22.         readBtn (Button) findViewById(R.id.read_btn);  
  23.         inputEv (EditText) findViewById(R.id.input_et);  
  24.         showEv (EditText) findViewById(R.id.showinfo_et);  
  25.         // 设置监听  
  26.         setListener();  
  27.      
  28.   
  29.       
  30.     public void setListener()  
  31.         saveBtn.setOnClickListener(new OnClickListener()  
  32.             public void onClick(View v)  
  33.                 boolean util.save("mykey"inputEv.getText().toString());  
  34.                 String msg;  
  35.                 if (b)  
  36.                     msg "保存成功" 
  37.                 else  
  38.                     msg "保存失败" 
  39.                  
  40.                 Toast.makeText(SharedPreferenced_DemoActivity.thismsg,  
  41.                         Toast.LENGTH_SHORT).show();  
  42.              
  43.         });  
  44.   
  45.         readBtn.setOnClickListener(new OnClickListener()  
  46.             public void onClick(View v)  
  47.                 System.out.println("read...");  
  48.                 String value util.read("mykey");  
  49.                 showEv.setText(value);  
  50.              
  51.         });  
  52.      
  53.   
  54.     @Override  
  55.     public void onCreate(Bundle savedInstanceState)  
  56.         super.onCreate(savedInstanceState);  
  57.         setContentView(R.layout.main);  
  58.         init();  
  59.      
  60.  
 



运行界面:

Android-SharedPreferences共享级别(单个activity,同一package下,application之间)



保存成功后我们可以找到相应的XML文件:

Android-SharedPreferences共享级别(单个activity,同一package下,application之间)


 
我们把XML文件提取出来打开,就可以看到我们保存的Key和Value了,小 平同志告诉我们:两手都要抓!




访问其他应用中的Preference


 I:访问本程序的(FirstApp)SharedPreferences中的数据代码如下:

 

Java代码   收藏代码
  1. SharedPreferences sharedPreferences getSharedPreferences("first_app_perferences"Context.MODE_PRIVATE);  
  2. String name sharedPreferences.getString("name""");  //getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值  
  3. int age sharedPreferences.getInt("age"1);  

 

 

II:访问其他应用中的Preference(在SecondApp中访问FirstApp的数据),前提条件是:FirstApp的preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。

如:在<packagename>为com.first.app的应用使用下面语句创建了preference("first_app_perferences")。

Java代码   收藏代码
  1. getSharedPreferences("first_app_perferences"Context.MODE_WORLD_READABLE);  

 

在SecondApp中要访问FirstApp应用中的preference,首先需要创建FirstApp应用的Context,然后通过Context 访问preference,访问preference时会在应用所在包下的shared_prefs目录找到preference :

Java代码   收藏代码
  1. Context firstAppContext createPackageContext("com.first.app"Context.CONTEXT_IGNORE_SECURITY);  
  2. SharedPreferences sharedPreferences firstAppContext.getSharedPreferences("first_app_perferences" Context.MODE_WORLD_READABLE);  
  3. String name sharedPreferences.getString("name""");  
  4. int age sharedPreferences.getInt("age"0);  

 

如果不通过创建Context访问FirstApp应用的preference,可以以读取xml文件方式直接访问FirstApp应用的preference对应的xml文件,如: 
File xmlFile = new File(“/data/data/<packagename>/shared_prefs/first_app_perferences.xml”);//<packagename>应替换成应用的包名: com.first.app


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值