• Android 不同应用通过SharedPreference实现共享数据


    Android不同应用之间数据的共享有许多方式,但是我觉得还是使用sharedPreference比较简单和轻量级。如果程序B想要访问程序A的sharedPreference可以通过下面的语句来实现:

    try {
        AContext =createPackageContext(A_PACKAGE_NAME,
                Context.CONTEXT_IGNORE_SECURITY);
    } catch (NameNotFoundException e) {
        Log.e(TAG, "find package error!");
    }
    SharedPreferences sp = AContext.getSharedPreferences(PREFERENCES_NAME,
            Context.MODE_WORLD_READABLE);
    sp.getInt(PREF_NAME, 0);

    当然在A程序里创建SharedPreference的时候也需要使用Context.MODE_WORLD_READABLE属性。另外 SharedPreference还有Context.MODE_WORLD_WRITEABLE属性。根据SDK的解释,就是允许别的应用程序来对 SharedPreference进行写操作。但是在实际程序实验中发现即使加上了这个属性,写操作也是无法成功的,会提示一个错误:Couldn't rename file /data/data/....PREFERENCES_NAME.XML to  /data/data/....PREFERENCES_NAME.XML.bak。这个错误的原因应该是很明确了,程序B在程序A的目录里面没有创建 和重命名文件的权限。

     
         那么到底要怎么样才能让程序B在程序A的SharedPreferences里面写东西呢,其实很简单,在manifest.xml里面将两个应用程序 的android:sharedUserId属性设为相同的就可以了。而且SharedPreference的属性也不需要 Context.MODE_WORLD_WRITEABLE了,只需要Context.MODE_PRIVATE也可以完成读写操作。
     
     
     
     
     
     
     
     
    示例:
    保存或创建一个preference:
    package edu.cczu.SimplePreference;  
    
    import android.app.Activity;  
    import android.content.Context;  
    import android.content.SharedPreferences;  
    import android.os.Bundle;  
    import android.widget.EditText;  
    
    public class SimplePreferenceActivity extends Activity {  
        private EditText nameText;  
        private EditText ageText;  
        private EditText heightText;  
        public static final String PREFER_NAME = "SaveSet";  
        public static int MODE = Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE;  
    
        /** Called when the activity is first created. */  
        @Override  
            public void onCreate(Bundle savedInstanceState) {  
                super.onCreate(savedInstanceState);  
                setContentView(R.layout.main);  
    
                nameText = (EditText)findViewById(R.id.name);  
                ageText = (EditText)findViewById(R.id.age);  
                heightText = (EditText)findViewById(R.id.height);  
            }  
    
        @Override  
            protected void onStart() {  
                // TODO Auto-generated method stub  
                super.onStart();  
                loadSharedPreferences();  
            }  
    
        private void loadSharedPreferences() {  
            // TODO Auto-generated method stub  
            SharedPreferences share = getSharedPreferences(PREFER_NAME, MODE);  
            String name = share.getString("Name", "Tom");  
            int age = share.getInt("Age", 20);  
            float height = share.getFloat("Height", 1.81f);  
    
            nameText.setText(name);  
            ageText.setText(String.valueOf(age));  
            heightText.setText(String.valueOf(height));  
        }  
    
        @Override  
            protected void onStop() {  
                // TODO Auto-generated method stub  
                super.onStop();  
                saveSharedPreferences();  
            }  
    
        private void saveSharedPreferences() {  
            // TODO Auto-generated method stub  
            SharedPreferences share = getSharedPreferences(PREFER_NAME, MODE);  
            SharedPreferences.Editor editor = share.edit();  
    
            editor.putString("Name", nameText.getText().toString());  
            editor.putInt("Age", Integer.parseInt(ageText.getText().toString()));  
            editor.putFloat("Height", Float.parseFloat(heightText.getText().toString()));  
            editor.commit();          
        }      
    }

    其他应用来读取数据:

    package edu.cczu.SharePreference;  
    
    import android.app.Activity;  
    import android.content.Context;  
    import android.content.SharedPreferences;  
    import android.content.pm.PackageManager.NameNotFoundException;  
    import android.os.Bundle;  
    import android.util.Log;  
    import android.widget.TextView;  
    import android.widget.Toast;  
    
    public class SharePreferenceActivity extends Activity {  
        public static final String PREFERENCE_PACKAGE = "edu.cczu.SimplePreference";  
        public static final String PREFERENCE_NAME = "SaveSet";  
        public static int MODE = Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE;  
        private TextView labelView;  
        private static String TAG = "LIFECYCLE";  
    
        /** Called when the activity is first created. */  
        @Override  
            public void onCreate(Bundle savedInstanceState) {  
                super.onCreate(savedInstanceState);  
                setContentView(R.layout.main);  
    
                Context c = null;  
                labelView = (TextView)findViewById(R.id.label);    
    
                try {  
                    c = this.createPackageContext(PREFERENCE_PACKAGE, Context.CONTEXT_IGNORE_SECURITY);  
    
                } catch (NameNotFoundException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }     
    
                SharedPreferences sharedPreferences = c.getSharedPreferences(PREFERENCE_NAME, MODE);  
    
                String name = sharedPreferences.getString("Name","Tom");  
                int age = sharedPreferences.getInt("Age", 20);  
                float height = sharedPreferences.getFloat("Height",1.81f);  
    
                String msg = "";  
                msg += "姓名:" + name + "
    ";  
                msg += "年龄:" + String.valueOf(age) + "
    ";  
                msg += "身高:" + String.valueOf(height) + "
    ";     
    
                labelView.setText(msg);     
    
                Toast.makeText(this, name, Toast.LENGTH_SHORT).show();  
    
                Log.i(TAG, "(1) onCreate()");  
            }  
    
        @Override  
            protected void onStart() {  
                // TODO Auto-generated method stub  
                super.onStart();  
                Log.i(TAG, "(2) onStart()");  
            }  
    
        @Override  
            protected void onStop() {  
                // TODO Auto-generated method stub  
                super.onStop();  
                Log.i(TAG, "(8) onStop()");  
            }  
    
        @Override  
            protected void onDestroy() {  
                // TODO Auto-generated method stub  
                super.onDestroy();  
                Log.i(TAG, "(9) onDestroy()");  
                //System.exit(0);  
            }      
    } 

  • 相关阅读:
    android入门
    jquery实现市,县级联
    java基础学习笔记五(抽象类)
    java基础学习笔记四(异常)
    java基础学习笔记三(多态)
    java基础学习笔记二(接口、super、this)
    java基础学习笔记一
    实习第二十二天
    武汉第二十一天
    武汉第二十天
  • 原文地址:https://www.cnblogs.com/welhzh/p/5644360.html
Copyright © 2020-2023  润新知