歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Android 將activity中的對象傳遞到service中

Android 將activity中的對象傳遞到service中,首先,寫一個類,這個是保存activity中的對象。在AndroidManifest.xml文件中的<application>標簽中寫入<application android:label="@string/app_name" android:icon="@drawable/icon"android:name=".SaveSth">

[java]
  1. public class SaveSth extends Application{  
  2.     private Against against;  
  3.     private PowerManager powerManager;  
  4.     public PowerManager getPowerManager() {  
  5.         return powerManager;  
  6.     }  
  7.   
  8.     public void setPowerManager(PowerManager powerManager) {  
  9.         this.powerManager = powerManager;  
  10.     }  
  11.   
  12.     public KeyguardLock getKeyguardLock() {  
  13.         return keyguardLock;  
  14.     }  
  15.   
  16.     public void setKeyguardLock(KeyguardLock keyguardLock) {  
  17.         this.keyguardLock = keyguardLock;  
  18.     }  
  19.   
  20.     private KeyguardLock keyguardLock ;  
  21.     public Against getAgainst() {  
  22.         return against;  
  23.     }  
  24.   
  25.     public void setAgainstTheft(Against against) {  
  26.         this.against = against;  
  27.     }  
  28. }  
第二步,在activity中將要傳遞的對象set進方法中。

[java]
  1. PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);  
  2. KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);  
  3. KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("");  
  4.   
  5. ((SaveSth)getApplication()).setAgainst(this);  
  6. ((SaveSth)getApplication()).setPowerManager(pm);  
  7. ((SaveSth)getApplication()).setKeyguardLock(keyguardLock);  
第三步,在service中取

[java]
  1. private Against against;  
  2. PowerManager pm;  
  3. PowerManager.WakeLock wakeLock;  
  4. KeyguardLock keyguardLock ;  
  5.   
  6. against= ((SaveSth)getApplication()).getAgainstTheft();  
  7. pm= ((SaveSth)getApplication()).getPowerManager();  
  8. keyguardLock=((SaveSth)getApplication()).getKeyguardLock();  
Copyright © Linux教程網 All Rights Reserved