下面这个程序就是通过其他程序访问上面的程序的SharedPreference.
- package cn.jason.io;
- import Android.app.Activity;
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.content.pm.PackageManager.NameNotFoundException;
- import android.os.Bundle;
- import android.widget.TextView;
- public class ReadOtherPreferenceActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Context useCount = null;
- try {
- useCount = createPackageContext("cn.jason.store", Context.CONTEXT_IGNORE_SECURITY);
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
- SharedPreferences preferences = useCount.getSharedPreferences("jason", Context.MODE_WORLD_READABLE);
- // 读取数据
- int num = preferences.getInt("num", 0);
- TextView show = (TextView) findViewById(R.id.show);
- // 显示读取的数据内容
- show.setText("" + num );
- }
- }
上面的代码关键是先建立报级别的上下文,然后读取到其他包的SharedPreferences。
更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11
