如何从Android中其他应用程序的其他应用程序的共享首选项中获取价值?

时间:2016-09-30 11:40:50

标签: android

我有两个app假设" AppOne"和#34; AppTwo",在AppOne中我有一些值存储在它的共享Prefrence中,例如" String" name",我希望从" appTwo&#获得此值34;。我怎么能这样做

AppOne Sahred偏好代码: -

private SharedPreferences m_Preference;
private SharedPreferences.Editor m_Editor;
private final String MY_PREF="AppData";

public PreferenceHelper(Context context){
    this.m_Preference = context.getSharedPreferences(MY_PREF,Context.MODE_PRIVATE);
    this.m_Editor = m_Preference.edit();
}
/*Saving String value......*/
public void saveStringPreference(String key,String value){
    m_Editor.putString(key,value);
    m_Editor.apply();
}
public String getStringPreference(String key){
    return m_Preference.getString(key,"");
}

/*Saving int value........*/
public void saveIntegerValue(String key,int value){
    m_Editor.putInt(key,value);
    m_Editor.apply();
}
public int getIntPreference(String key){
    return m_Preference.getInt(key,1);
}

在MainActivity中我保存了这个值: -

preferenceHelper = new PreferenceHelper(getApplicationContext());

    preferenceHelper.saveStringPreference("Name", "ABC");

2 个答案:

答案 0 :(得分:0)

你做不到。 SharedPreferences是应用程序包的本地,无法直接从外部访问(出于安全原因,最有可能)。

如果您希望其他应用能够从您的应用中获取某些数据(SharedPrefs或任何其他数据),则需要定义ContentProviderBroadcastReceiver,{{ 1}}或外部(网络)api: - )

答案 1 :(得分:0)

为什么不编写文件而不是使用sharedPreferences来存储某些数据。 通过这种方式,您可以从另一个Android应用程序访问数据。

写一个txt文件

public void writeToFile(String data)
{
    // Get the directory for the user's public pictures directory.
    final File path =
        Environment.getExternalStoragePublicDirectory
        (
            //Environment.DIRECTORY_PICTURES
            Environment.DIRECTORY_DCIM + "/YourFolder/"
        );

    // Make sure the path directory exists.
    if(!path.exists())
    {
        // Make it, if it doesn't exit
        path.mkdirs();
    }

    final File file = new File(path, "myText.txt");

    // Save your stream, don't forget to flush() it before closing it.

    try
    {
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(data);

        myOutWriter.close();

        fOut.flush();
        fOut.close();
    }
    catch (IOException e)
    {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

阅读文件:

public String readTheFile(){
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"myText.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}
 return text.toString();
}