• 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);  
            }      
    } 

  • 相关阅读:
    [转]如何让ruby中的ri起作用
    大四中软实习笔记20130304
    VC6.0: fatal error C1010: unexpected end of file while looking for precompiled head
    大四中软实习笔记20130307
    C++ odbc 连接数据库错误 在指定的 DSN 中,驱动程序和应用程序之间的体系结构不匹配
    大四中软实习笔记20130303
    VC6.0: unresolved external symbol "public
    【分布式锁的演化】什么是锁?
    【分布式锁的演化】常用锁的种类以及解决方案
    【数据库】海量数据切分方案
  • 原文地址:https://www.cnblogs.com/welhzh/p/5644360.html
Copyright © 2020-2023  润新知