Start new activity using onShake method

我与影子孤独终老i 提交于 2019-12-11 07:45:17

问题


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.


回答1:


Use unregisterListener() in onPause().




回答2:


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 the onShake() method gets called, your activity will not start since your instance variable is now set to true.



来源:https://stackoverflow.com/questions/7067633/start-new-activity-using-onshake-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!