2011-07-19 8 views
15

Po naciśnięciu przycisku Wstecz muszę przekazać wartość boolowską i zamiar, i ponownie. Celem jest ustawienie wartości logicznej i użycie warunku, aby zapobiec wielokrotnemu uruchamianiu nowego zamiaru po wykryciu zdarzenia onShake. Używałbym SharedPreferences, ale wygląda na to, że nie gra on dobrze z moim kodem onClick i nie jestem pewien, jak to naprawić. Wszelkie sugestie będą mile widziane!Jak przekazać wartość logiczną między intencjami

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(); 
}} 

Odpowiedz

6

mieć prywatną zmienną składową aktywności zwanej wasShaken.

private boolean wasShaken = false; 

zmodyfikuj swój plik onResume, aby ustawić tę wartość na false.

public void onResume() { wasShaken = false; } 

w odbiorniku onShake, sprawdź, czy to prawda. jeśli tak, powróć wcześniej. Następnie ustaw go na 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

dokładnie to, czego potrzebowałem, dzięki! :) – Carnivoris

63

Ustaw zamiar extra (z putExtra):

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

Odzyskaj zamiar dodatkowo:

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