2011-07-19 7 views
15

Necesito pasar un valor booleano a intency y viceversa cuando se presiona el botón Atrás. El objetivo es establecer el booleano y usar un condicional para evitar lanzamientos múltiples de un nuevo intento cuando se detecta un evento onShake. Usaría SharedPreferences, pero parece que no funciona bien con mi código onClick y no estoy seguro de cómo solucionarlo. ¡Cualquier sugerencia sera apreciada!Cómo pasar un valor booleano entre los intentos

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

Respuesta

6

tienen una variable miembro privada en su actividad llamada wasShaken.

private boolean wasShaken = false; 

modifique su onResume para establecer esto en falso.

public void onResume() { wasShaken = false; } 

en su OnShake oyente, verifique si es verdadero. si es así, regresa temprano. Luego configúralo en verdadero.

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

exactamente lo que necesitaba, gracias! :) – Carnivoris

63

Establecer la intención adicional (con putExtra):

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

Recuperar la intención adicional:

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