2013-07-05 205 views
1

後保存到意向我的申請,我使用一個意圖:屏幕旋轉

private Handler mHandler = new Handler(); 
. 
. 
mServiceIntent = new Intent(this, ObdGatewayService.class); 
mServiceConnection = new ObdGatewayServiceConnection(); 
mServiceConnection.setServiceListener(mListener); 
// bind service 
Log.d(TAG, "Binding service.."); 
bindService(mServiceIntent, mServiceConnection, 
       Context.BIND_AUTO_CREATE); 

這裏我在的onCreate活動開始一個新的服務。這是我的onDestroy:

@Override 
protected void onDestroy() { 
    super.onDestroy(); 

    mServiceIntent = null; 
    mServiceConnection = null; 
    mListener = null; 
    mHandler = null; 
} 

這是mServiceConnection:

public class ObdGatewayServiceConnection implements ServiceConnection{ 

private static final String TAG = "com.echodrive.io.ObdGatewayServiceConnection"; 

private IPostMonitor service = null; 
private IPostListener listener = null; 

public void onServiceConnected(ComponentName name, IBinder binder) { 
    service = (IPostMonitor) binder; 
    service.setListener(listener); 
} 


public void onServiceDisconnected(ComponentName name) { 
    service = null; 
    Log.d(TAG, "Service disconnesso."); 
} 


public boolean isRunning() { 
    if (service == null) { 
     return false; 
    } 

    return service.isRunning(); 
} 


public void addJobToQueue(ObdCommandJob job) { 
    if (null != service) 
     service.addJobToQueue(job); 
} 

public void setServiceListener(IPostListener listener) { 
    this.listener = listener; 
} 

mListener是從接口的監聽器:

public interface IPostListener { 
void fineTest(DatiTest risultati); 
void startAcquisizione(); 
void aquisizioneTerminata(); 
void aquisizioneInterrotta(String motivo); 
void connessioneCorretta(); 
void gpsStato(boolean stato); 
} 

我的問題是如何..保存所有這些代碼旋轉後?謝謝!

回答

2

跨旋轉保存狀態的推薦方法是將它們保存在outState上。這是通過覆蓋onSaveInstanceState方法來完成的。此方法爲您提供Bundle outState對象,您可以將ParcelableSerializable對象添加到。這應該適用於您的Intent對象,因爲它實現Parcelable,但它可能不適用於說Handler,因爲它只擴展Object

另一個解決方案是使這些成員爲靜態。但是,如果您決定這樣做,請非常小心。確保靜態成員的值永遠不會保留在Context或視圖層次結構等中,否則您可能很容易引入內存泄漏。

如果這些都不能被您接受,Tushar會提出這個選項。但是,除非你小心,否則這會讓你的生活非常困難。活動被破壞和重新創建的一個重要原因是資源可以重新加載。因此,如果您有佈局,字符串,顏色,維度或基本上任何專門針對橫向,平板電腦或不同版本的資源,則必須自行重新加載整個用戶界面。