Car*_*ris 18 android shake android-intent
当按下后退按钮时,我需要将布尔值传递给intent,然后再返回intent.目标是设置布尔值并使用条件来防止在检测到onShake事件时多次启动新意图.我会使用SharedPreferences,但似乎它与我的onClick代码不相配,我不知道如何解决这个问题.任何建议,将不胜感激!
public class MyApp extends Activity {
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSensorListener = new ShakeEventListener();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
// This code is launched multiple times on a vigorous
// shake of the device. I need to prevent this.
Intent myIntent = new Intent(MyApp.this, NextActivity.class);
MyApp.this.startActivity(myIntent);
}
});
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onStop() {
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}}
Run Code Online (Sandbox Code Playgroud)
cit*_*onn 73
设置intent额外(使用putExtra):
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("yourBoolName", true);
Run Code Online (Sandbox Code Playgroud)
检索额外意图:
@Override
protected void onCreate(Bundle savedInstanceState) {
Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName");
}
Run Code Online (Sandbox Code Playgroud)
在您的活动中有一个名为wasShaken的私有成员变量.
private boolean wasShaken = false;
Run Code Online (Sandbox Code Playgroud)
修改你的onResume以将其设置为false.
public void onResume() { wasShaken = false; }
Run Code Online (Sandbox Code Playgroud)
在你的onShake监听器中,检查它是否属实.如果是的话,早点回来.然后将其设置为true.
public void onShake() {
if(wasShaken) return;
wasShaken = true;
// This code is launched multiple times on a vigorous
// shake of the device. I need to prevent this.
Intent myIntent = new Intent(MyApp.this, NextActivity.class);
MyApp.this.startActivity(myIntent);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44214 次 |
| 最近记录: |