使用 onShake 方法启动新活动
我想通过使用 onShake 方法开始新的活动。一切正常,但是当新活动开始时,onShake 命令仍然可以使用(当我摇动手机 5 次时,新活动启动 5 次)。我应该怎么做才能摇动手机并仅开始新活动一次? 这是我的代码。
public class ACTIVITY extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SensorManager mSensorManager;
ShakeEvent mSensorListener;
mSensorListener = new ShakeEvent();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
mSensorListener.setOnShakeListener(new ShakeEvent.OnShakeListener() {
public void onShake() {
Intent i = new Intent(Shake.this, NEWACTIVITY.class);
startActivity(i);
}
});
}}
请原谅我的英语不好。谢谢你的帮助。
I'd like to start new activity by using onShake method. Everything is ok but when new activity starts, onShake command is still possible (when i shake my phone 5 times, new activity starts 5 times). What should I do to shake phone and start new activity only once?
Here is my code.
public class ACTIVITY extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SensorManager mSensorManager;
ShakeEvent mSensorListener;
mSensorListener = new ShakeEvent();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
mSensorListener.setOnShakeListener(new ShakeEvent.OnShakeListener() {
public void onShake() {
Intent i = new Intent(Shake.this, NEWACTIVITY.class);
startActivity(i);
}
});
}}
Excuse me for my bad English. Thank you for help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 unregisterListener () 在
onPause()
中。Use unregisterListener() in
onPause()
.使用实例变量(布尔值)并将其最初设置为 false。第一次调用
onShake()
时,在启动新 Activity 之前检查它是否为 false。然后将其更改为 true 并启动活动。下次调用onShake()
方法时,您的 Activity 将不会启动,因为您的实例变量现已设置为 true。Use an instance variable(a boolean) and keep it set to false initially. When
onShake()
is called the first time, check if it is false before starting the new activity. Then change it to true and start the activity. The next time theonShake()
method gets called, your activity will not start since your instance variable is now set to true.