问题
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