Android 将activity中的对象传递到service中

首先,写一个类,这个是保存activity中的对象。在AndroidManifest.xml文件中的<application>标签中写入<application android:label="@string/app_name" android:icon="@drawable/icon"android:name=".SaveSth">

public class SaveSth extends Application{
	private Against against;
	private PowerManager powerManager;
	public PowerManager getPowerManager() {
		return powerManager;
	}

	public void setPowerManager(PowerManager powerManager) {
		this.powerManager = powerManager;
	}

	public KeyguardLock getKeyguardLock() {
		return keyguardLock;
	}

	public void setKeyguardLock(KeyguardLock keyguardLock) {
		this.keyguardLock = keyguardLock;
	}

	private KeyguardLock keyguardLock ;
	public Against getAgainst() {
		return against;
	}

	public void setAgainstTheft(Against against) {
		this.against = against;
	}
}
第二步,在activity中将要传递的对象set进方法中。

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("");

((SaveSth)getApplication()).setAgainst(this);
((SaveSth)getApplication()).setPowerManager(pm);
((SaveSth)getApplication()).setKeyguardLock(keyguardLock);
第三步,在service中取

private Against against;
PowerManager pm;
PowerManager.WakeLock wakeLock;
KeyguardLock keyguardLock ;

against= ((SaveSth)getApplication()).getAgainstTheft();
pm= ((SaveSth)getApplication()).getPowerManager();
keyguardLock=((SaveSth)getApplication()).getKeyguardLock();




你可能感兴趣的:(Android 将activity中的对象传递到service中)