2011-07-19 61 views
15

我需要傳遞一個布爾值並且意圖,並且當按下後退按鈕時再次返回。目標是設置布爾值並使用條件來防止在檢測到onShake事件時多次啓動新的intent。我會使用SharedPreferences,但它似乎不適合我的onClick代碼,我不知道如何解決這個問題。任何建議,將不勝感激!如何在意圖之間傳遞布爾值

public class MyApp extends Activity { 

private SensorManager mSensorManager; 
private ShakeEventListener mSensorListener; 


/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 


    mSensorListener = new ShakeEventListener(); 
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 
    mSensorManager.registerListener(mSensorListener, 
     mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
     SensorManager.SENSOR_DELAY_UI); 


    mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() { 

     public void onShake() { 
      // This code is launched multiple times on a vigorous 
      // shake of the device. I need to prevent this. 
      Intent myIntent = new Intent(MyApp.this, NextActivity.class); 
      MyApp.this.startActivity(myIntent); 
     } 
    }); 

} 

@Override 
protected void onResume() { 
    super.onResume(); 
    mSensorManager.registerListener(mSensorListener,mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
     SensorManager.SENSOR_DELAY_UI); 
} 

@Override 
protected void onStop() { 
    mSensorManager.unregisterListener(mSensorListener); 
    super.onStop(); 
}} 

回答

6

在你的活動稱爲wasShaken一個私有成員變量。

private boolean wasShaken = false; 

修改您的onResume將其設置爲false。

public void onResume() { wasShaken = false; } 

在你的onShake偵聽器中,檢查它是否爲真。如果是的話,儘早回來。然後將其設置爲true。

public void onShake() { 
       if(wasShaken) return; 
       wasShaken = true; 
          // This code is launched multiple times on a vigorous 
          // shake of the device. I need to prevent this. 
       Intent myIntent = new Intent(MyApp.this, NextActivity.class); 
       MyApp.this.startActivity(myIntent); 
    } 
}); 
+0

正是我所需要的,謝謝! :) – Carnivoris

63

設置額外的意向(含putExtra):

Intent intent = new Intent(this, NextActivity.class); 
intent.putExtra("yourBoolName", true); 

獲取額外的意圖:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName"); 
}