Android五大存储方法之一的SharedPreferences,要保存应用变量值的时候非常有用,这里给出SharedPreferences的封装,方便其他类直接使用
新建SharePreUtil类
<span style="font-size:18px;">public class SharePreUtil { SharedPreferences share; Context ctx; public SharePreUtil(Context ctx) { super(); this.ctx = ctx; share = ctx.getSharedPreferences("share", 0);//share为存储名称 }</span>
添加put 和get方法
<span style="font-size:18px;">//存取数据 public void putFirstUse(int firstUse){ share.edit().putInt("firstUse", firstUse).commit(); } public int getFirstUse(){ int firstUse = share.getInt("firstUse", 0); return firstUse; }</span>
这样其他类就可以通过SharePreUtil直接使用SharedPreferences了
<span style="font-size:18px;">SharePreUtil sharePreUtil ; sharePreUtil = new SharePreUtil(getApplicationContext());//传Context put、get操作 sharePreUtil.putFirstUse(1); sharePreUtil.getFristUse();</span>