如何在意图之间传递布尔值

时间:2011-07-19 17:41:46

标签: android android-intent shake

当按下后退按钮时,我需要将布尔值传递给意图并再次返回。目标是设置布尔值并使用条件来防止在检测到onShake事件时多次启动新意图。我会使用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();
}}

3 个答案:

答案 0 :(得分:71)

设置intent extra(使用putExtra):

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

检索额外意图:

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

答案 1 :(得分: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);
  }
});

答案 2 :(得分:0)

这是您在Kotlin中的工作方式:

val intent = Intent(this@MainActivity, SecondActivity::class.java)
            intent.putExtra("sample", true)
            startActivity(intent)

var sample = false
sample = intent.getBooleanExtra("sample", sample)
println("sample")

输出样本= true