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 set
		return (!settings.getString(USERNAME_KEY, "").equals(""));
	}
 
}

上面没有特殊的作用 就是暂时的储存,如果想将上面的储存作为全局变量需要

public class MyApp extends Application {
 
	private Settings settings;
 
	@Override
	public 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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值