ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### 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://box.kancloud.cn/2016-04-06_5704ccedee14d.jpg) ![](https://box.kancloud.cn/2016-04-06_5704ccee14e9e.jpg) ![](https://box.kancloud.cn/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://box.kancloud.cn/2016-04-06_5704ccee3c181.jpg) ### 3、关于android:sharedUserId 上面的两个工程中并没有对android:sharedUserId属性进行设置。这个属性是在查资料时看到的:意思是说,在manifest.xml里面将两个应用程序的android:sharedUserId属性设为相同的就可以对SharedPreferences文件进行写。(此处并没有验证)