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

编程入门 行业动态 更新时间:2024-10-28 15:22:15
本文介绍了如何在意图之间传递布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要将一个布尔值传递给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); } });

更多推荐

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

本文发布于:2023-11-27 14:51:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意图   如何在   布尔值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!