【问题标题】:Start new activity using onShake method使用 onShake 方法启动新活动
【发布时间】:2011-08-15 16:22:49
【问题描述】:

我想使用 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);
      }
    });
}}

对不起,我的英语不好。谢谢你的帮助。

【问题讨论】:

    标签: android android-activity shake


    【解决方案1】:

    onPause() 中使用unregisterListener()

    【讨论】:

      【解决方案2】:

      使用一个实例变量(一个布尔值)并保持它最初设置为 false。当onShake()第一次被调用时,在开始新的activity之前检查它是否为false。然后将其更改为 true 并开始活动。下次调用 onShake() 方法时,您的活动将不会启动,因为您的实例变量现在设置为 true。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-26
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        相关资源
        最近更新 更多