SharedPreferences使用二

来源:互联网 发布:macbook装office软件 编辑:程序博客网 时间:2024/05/29 17:56

访问其他应用的SharedPreferences

main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" /></LinearLayout>


ActivityMain

package com.android2;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.os.Bundle;import android.widget.Toast;public class ActivityMain extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);       /* 要访问其他应用的SharedPreferences,首先需要创建其他应用的Context,                          然后通过Context访问SharedPreferences ,                          会在应用所在包下的shared_prefs目录找到SharedPreference的xml文件       */        Context otherAppsContext = null;                try { otherAppsContext = createPackageContext("com.android", Context.CONTEXT_IGNORE_SECURITY);        } catch (Exception e) {e.printStackTrace();}        if(otherAppsContext!=null){        SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("test", Context.MODE_WORLD_READABLE);String name = sharedPreferences.getString("name", "");int age = sharedPreferences.getInt("age", 0);    Toast.makeText(this, "name:"+name+",age:"+age, Toast.LENGTH_LONG).show();        }    }}


0 0
原创粉丝点击