如何在意图之间传递布尔值 [英] How to pass a boolean between intents

查看:231
本文介绍了如何在意图之间传递布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个布尔值传递给and intent,然后在按下后退按钮时再次将其返回.目标是设置布尔值并使用条件,以防止在检测到onShake事件时多次启动新的意图.我会使用SharedPreferences,但是似乎它与我的onClick代码配合使用不太好,而且我不确定如何解决该问题.任何建议,将不胜感激!

I need to pass a boolean value to and intent and back again when the back button is pressed. The goal is to set the boolean and use a conditional to prevent multiple launches of a new intent when an onShake event is detected. I would use SharedPreferences, but it seems it does not play nice with my onClick code and I'm not sure how to fix that. Any suggestions would be appreciated!

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

推荐答案

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

have a private member variable in your activity called wasShaken.

private boolean wasShaken = false;

修改您的onResume将此值设置为false.

modify your onResume to set this to false.

public void onResume() { wasShaken = false; }

在您的onShake侦听器中,

检查它是否正确.如果是,请早点回来.然后将其设置为true.

in your onShake listener, check if it's true. if it is, return early. Then set it to 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);
  }
});

这篇关于如何在意图之间传递布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆