Start new activity using onShake method
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(savedInstanceS开发者_Python百科tate);
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.
Use unregisterListener() in onPause()
.
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.
精彩评论