您的位置:首页 > 移动开发 > Android开发

Android SharedPreferences读取外部程序的SharedPreferences存储

2015-09-14 17:05 176 查看
import org.crazyit.other.R;

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 ReadOtherPreferences extends Activity
{
     @Override
     public void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          Context useCount = null;
          try
          {
          <span style="color:#ff0000;"> <strong>    // 获取其他程序所对应的Context,这里非常关键,是读取别的程序的包明!</strong></span>
               useCount = createPackageContext("org.crazyit.io",
                    Context.CONTEXT_IGNORE_SECURITY);
          }
          catch (NameNotFoundException e)
          {
               e.printStackTrace();
          }
          // 使用其他程序的Context获取对应的SharedPreferences
          SharedPreferences prefs = useCount.getSharedPreferences("count",
               Context.MODE_WORLD_READABLE);
          // 读取数据
          int count = prefs.getInt("count", 0);
          TextView show = (TextView) findViewById(R.id.show);
          // 显示读取的数据内容
          show.setText("UseCount应用程序以前被使用了" + count + "次。");
     }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: