19

ブール値をインテントに渡して、戻るボタンが押されたときに再び戻る必要があります。目標は、ブール値を設定し、条件を使用して、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();
}}
4

3 に答える 3

79

インテント エクストラを設定します (putExtra を使用):

Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("yourBoolName", true);

インテント エクストラを取得します。

@Override
protected void onCreate(Bundle savedInstanceState) {
    Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName");
}
于 2011-07-19T17:48:05.233 に答える
6

アクティビティに wasShaken というプライベート メンバー変数があります。

private boolean wasShaken = false;

onResume を変更して、これを false に設定します。

public void onResume() { wasShaken = false; }

onShake リスナーで、それが true かどうかを確認します。もしそうなら、早く戻ってください。次に、それを 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);
  }
});
于 2011-07-19T17:56:52.163 に答える
3

Kotlin で行う方法は次のとおりです。

val intent = Intent(this@MainActivity, SecondActivity::class.java)
            intent.putExtra("sample", true)
            startActivity(intent)

var sample = false
sample = intent.getBooleanExtra("sample", sample)
println(sample)

出力サンプル = true

于 2019-10-28T11:11:14.803 に答える