Android 將activity中的對象傳遞到service中,首先,寫一個類,這個是保存activity中的對象。在AndroidManifest.xml文件中的<application>標簽中寫入<application android:label="@string/app_name" android:icon="@drawable/icon"android:name=".SaveSth">
[java]
- 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進方法中。
[java]
- 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中取
[java]
- private Against against;
- PowerManager pm;
- PowerManager.WakeLock wakeLock;
- KeyguardLock keyguardLock ;
-
- against= ((SaveSth)getApplication()).getAgainstTheft();
- pm= ((SaveSth)getApplication()).getPowerManager();
- keyguardLock=((SaveSth)getApplication()).getKeyguardLock();