activity之间全局变量的使用
import uk.co.kraya.HelloWS;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor; public class Settings { private static final String USERNAME_KEY = "username";private static final String PASSWORD_KEY = "password"; private static final String USERNAME_DEFAULT = "username";private static final String PASSWORD_DEFAULT = "password"; private final SharedPreferences settings; /** * @param act The context from which to pick SharedPreferences */public Settings (Context act) { settings = act.getSharedPreferences(HelloWS.PREFS_NAME, Context.MODE_PRIVATE);} /** * Set the username in the preferences. * * @param username the username to save into prefs */public void setUsername(String username) {Editor editor = settings.edit();editor.putString(USERNAME_KEY, username);editor.commit();} /** * @return the username from the prefs */public String getUsername() {return settings.getString(USERNAME_KEY, USERNAME_DEFAULT);} /** * * Set the password in the preferences. * * @param password password to save into prefs */public void setPassword(String password) {Editor editor = settings.edit();editor.putString(PASSWORD_KEY, password);editor.commit();} /** * @return the password stored in prefs */public String getPassword() {return settings.getString(PASSWORD_KEY, PASSWORD_DEFAULT);} public boolean hasSettings() {// We just check if a username has been setreturn (!settings.getString(USERNAME_KEY, "").equals(""));} }上面没有特殊的作用 就是暂时的储存,如果想将上面的储存作为全局变量需要
public class MyApp extends Application { private Settings settings; @Overridepublic void onCreate() {settings = new Settings(this); } public Settings getSettings() {return settings;} }?继承了Application,其中的onCreate() 比任何活动中的onCreate() 执行的要早,所以可以将变量取出来使用,
不过别忘了 需要在主xml中注明
<application android:name="com.package.MyApp" android:icon="@drawable/icon" android:label="@string/app_name">
?使用就很简单了
MyApp app = (MyApp) getApplicationContext();?Settings settings = app.getSettings();1 楼 enjoylrx 2011-09-30 博主你好,想问一下既然Settings封装了SharedPreferences,Settings并不需要全局同一,现在这样做好像更加麻烦了,如果需要经常调用Settings的方法何不直接把它们都声明为静态呢?