【3D技术宅公社】XR数字艺术论坛  XR技术讨论 XR互动电影 定格动画

 找回密码
 立即注册

QQ登录

只需一步,快速开始

调查问卷
论坛即将给大家带来全新的技术服务,面向三围图形学、游戏、动画的全新服务论坛升级为UTF8版本后,中文用户名和用户密码中有中文的都无法登陆,请发邮件到324007255(at)QQ.com联系手动修改密码

3D技术论坛将以计算机图形学为核心,面向教育 推出国内的三维教育引擎该项目在持续研发当中,感谢大家的关注。

查看: 1833|回复: 0

利用SharedPreferences来保存应用程序的数据

[复制链接]
发表于 2013-5-19 22:37:49 | 显示全部楼层 |阅读模式
/********************************************************************************************
* author:conowen@大钟                                                                                                                          
* E-mail:conowen@hotmail.com                                                                                                            
* http://blog.csdn.net/conowen                                                                                                            
* 注:本文为原创,仅作为学习交流使用,转载请标明作者及出处。      

********************************************************************************************/


1、SharedPreferences的简单介绍

        应用程序在运行的时候,可能会随着用户的使用而保持该用户的配置信息,如上次播放时的eq设置,音量设置,上网的cookies信息等等,这些小量 的信息可以通过SharedPreferences来保持,通过SharedPreferences保持的数据为一个XML文件,位于应用程序的私有文件夹。

2、具体操作方法

获取SharedPreferences,可以通过以下方法获取

public SharedPreferences getSharedPreferences (String name, int mode)Since: API Level 1
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

Parameters
nameDesired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
modeOperating mode. Use 0 or MODE_PRIVATE for the default operation,MODE_WORLD_READABLE andMODE_WORLD_WRITEABLE to control permissions. The bitMODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file.MODE_MULTI_PROCESS is always 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 to retrieve and modify the preference values.





参数简述:

Name————获得SharedPreferences之后,将会在应用程序的私有文件夹中保存着一个XML文件,第一个参数name就是这个文件名字。

Mode————XML文件的保存模式,默认为0,也就是MODE_PRIVATE


3、简单的demo

通过service的一个音乐播放例子,“播放”与“暂停”两个按钮

暂停之后,保持播放进度到SharedPreferences里面,然后再次播放的话,读取进度值进行音乐播放。

  1. /*
  2. * @author:conowen
  3. * @date:12.3.01
  4. *
  5. */
  6. package com.conowen.sharedpreferences;

  7. import android.app.Activity;
  8. import android.content.Intent;
  9. import android.os.Bundle;
  10. import android.view.View;
  11. import android.view.View.OnClickListener;
  12. import android.widget.Button;

  13. public class SharedPreferencesActivity extends Activity {
  14.     /** Called when the activity is first created. */
  15.     @Override
  16.     public void onCreate(Bundle savedInstanceState) {
  17.         super.onCreate(savedInstanceState);
  18.         setContentView(R.layout.main);
  19.         Button play = (Button) findViewById(R.id.play);  
  20.         Button pause = (Button) findViewById(R.id.pause);  

  21.         final Intent intent = new Intent(SharedPreferencesActivity.this,service.class);  
  22.         // 定义intent为final,全局变量,供下面两个匿名内部类(onclicklisenter)使用  
  23.         play.setOnClickListener(new OnClickListener() {  
  24.   
  25.             @Override  
  26.             public void onClick(View v) {  
  27.                 // TODO Auto-generated method stub  
  28.                 startService(intent);  
  29.                 // 开始播放,通过前面定义好的intent传递  
  30.   
  31.             }  
  32.         });  
  33.         pause.setOnClickListener(new OnClickListener() {  
  34.   
  35.             @Override  
  36.             public void onClick(View v) {  
  37.                 // TODO Auto-generated method stub  
  38.                 stopService(intent);  
  39.                 // 停止播放  
  40.   
  41.             }  
  42.         });  
  43.         
  44.     }
  45. }
复制代码
第二个class是继承service的,记得在manifest.XML里面注册service
  1. /*
  2. * @author:conowen
  3. * @date:12.3.01
  4. *
  5. */
  6. package com.conowen.sharedpreferences;

  7. import android.app.Service;
  8. import android.content.Intent;
  9. import android.content.SharedPreferences;
  10. import android.media.MediaPlayer;
  11. import android.os.IBinder;

  12. public class service extends Service {

  13.         MediaPlayer player;

  14.         // 新建播放器

  15.         @Override
  16.         public void onCreate() {
  17.                 // TODO Auto-generated method stub
  18.                 super.onCreate();
  19.                 player = MediaPlayer.create(this, R.raw.lt26);
  20.                 player.setLooping(true);
  21.                 // 两种方式的第一个生命周期都是onCreate()
  22.         }

  23.         @Override
  24.         public void onStart(Intent intent, int startId) {
  25.                 // TODO Auto-generated method stub
  26.                 super.onStart(intent, startId);
  27.                 SharedPreferences sp = this.getSharedPreferences("music_progress",
  28.                                 MODE_PRIVATE);
  29.                 // music_progress为XML文件的文件名
  30.                 player.seekTo(sp.getInt("progress", 0));
  31.                 // progress为键值对中的key,progress所对应的值通过player.getCurrentPosition()获得,请看下面详细
  32.                 // 每次调用onStart方法时,就会设置player的进度
  33.                 // MediaPlayer的seekTo方法,读取进度,然后播放,getInt的第一个参数是所要读取的key名字,第二个参数为默认初始值。也就是说进度初始默认为0
  34.                 player.start();
  35.         }

  36.         @Override
  37.         public void onDestroy() {
  38.                 // TODO Auto-generated method stub
  39.                 super.onDestroy();
  40.                 SharedPreferences sp = this.getSharedPreferences("music_progress",
  41.                                 MODE_PRIVATE);
  42.                 sp.edit().putInt("progress", player.getCurrentPosition()).commit();
  43.                 // player.getCurrentPosition()方法获取播放进度的数据
  44.                 // commit()方法是保存SharedPreferences获取来的数据
  45.                 player.stop();
  46.         }

  47.         @Override
  48.         public IBinder onBind(Intent intent) {
  49.                 // TODO Auto-generated method stub
  50.                 return null;
  51.         }

  52. }
复制代码

通过SharedPreferences保存的文档如下所示,打开DDMS,切换到File Explore,在私有目录下的shared_prefs文件夹里面,路径为

/data/data/你的包名/shared_prefs



内容如下

  1. <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
  2. <map>
  3. <int name="progress" value="90695" />
  4. </map>
复制代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|3D数字艺术论坛 ( 沪ICP备14023054号 )

GMT+8, 2024-6-16 23:55

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表