19

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

3 回答 3

79

额外设置意图(使用 putExtra):

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

额外检索意图:

@Override
protected void onCreate(Bundle savedInstanceState) {
    Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName");
}
于 2011-07-19T17:48:05.233 回答
6

在您的活动中有一个名为 wasShaken 的私有成员变量。

private boolean wasShaken = false;

修改您的 onResume 以将其设置为 false。

public void onResume() { wasShaken = false; }

在你的 onShake 监听器中,检查它是否为真。如果是,请早点回来。然后将其设置为真。

  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);
  }
});
于 2011-07-19T17:56:52.163 回答
3

这就是你在 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

于 2019-10-28T11:11:14.803 回答