如何在不同的intent之间传递Boolean值

20

我需要在意图中传递布尔值,并在按下返回按钮时将其传回。目标是设置布尔值并使用条件语句来防止在检测到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个回答

81

设置意图附加信息(使用putExtra):

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

获取意图附加信息:

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

getIntent()现在已经过时。 - Roman Soviak
@user7856586 你有官方来源证明 getIntent 已经被弃用了吗? - nibbana

6

在你的活动中有一个私有成员变量叫做wasShaken。

private boolean wasShaken = false;

修改您的onResume方法,将其设置为false。

public void onResume() { wasShaken = false; }

在你的onShake监听器中,检查是否为true。如果是,则提前返回。然后将其设为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);
  }
});

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)

输出结果为真。


0

发送活动:

val intent: Intent = Intent(this, ReceiveActivity::class.java)

intent.putExtra("BOOLEAN_VALUE",true) startActivity(intent)

接收活动:

val condition = intent.getBooleanExtra("BOOLEAN_VALUE",false)

Log.d("Condition","接收到的值为:$condition")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接