不同APP通过SharedPreferences传递数据(共享数据)
最后更新于:2022-04-01 14:27:36
### 1、写入数据APP
~~~
public class MainActivity extends Activity {
private SharedPreferences putPreferences;
private Editor putEditor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 将服务器信息写入serverInfo.xml
findViewById(R.id.buttonPut).setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
putPreferences = getSharedPreferences("serverInfo", Context.MODE_WORLD_READABLE);
putEditor = putPreferences.edit();
putEditor.putString("serverIP", "192.168.1.102");
putEditor.putString("password", "123456");
putEditor.commit();
Toast.makeText(MainActivity.this,"服务器信息成功写入serverInfo.xml", Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
~~~
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-06_5704ccedee14d.jpg)
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-06_5704ccee14e9e.jpg)
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-06_5704ccee2c0e8.jpg)
### 2、获取数据APP
~~~
public class MainActivity extends Activity {
private SharedPreferences getPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//从serverInfo.xml获取服务器信息
findViewById(R.id.buttonGet).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Context context=createPackageContext("com.example.putprefapp", Context.CONTEXT_IGNORE_SECURITY);
getPreferences=context.getSharedPreferences("serverInfo", MODE_WORLD_READABLE);
String serverIP=getPreferences.getString("serverIP","");
String serverPwd=getPreferences.getString("password", "");
Toast.makeText(MainActivity.this, "服务器信息如下:IP地址:" +serverIP+"; 密码:"+serverPwd, Toast.LENGTH_LONG).show();
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
~~~
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-06_5704ccee3c181.jpg)
### 3、关于android:sharedUserId
上面的两个工程中并没有对android:sharedUserId属性进行设置。这个属性是在查资料时看到的:意思是说,在manifest.xml里面将两个应用程序的android:sharedUserId属性设为相同的就可以对SharedPreferences文件进行写。(此处并没有验证)