2011-07-19 23 views
15

Tôi cần phải chuyển giá trị boolean đến và ý định và quay trở lại khi nhấn nút quay lại. Mục tiêu là đặt boolean và sử dụng một điều kiện để ngăn chặn nhiều lần khởi chạy của một mục đích mới khi phát hiện sự kiện onShake. Tôi sẽ sử dụng SharedPreferences, nhưng có vẻ như nó không chơi tốt đẹp với mã onClick của tôi và tôi không chắc chắn cách khắc phục điều đó. Mọi lơi đê nghị đêu nên được đanh gia cao!Làm thế nào để vượt qua một boolean giữa các mục

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(); 
}} 

Trả lời

6

có một biến thành viên tư nhân trong hoạt động của bạn được gọi là wasShaken.

private boolean wasShaken = false; 

sửa đổi onResume của bạn để đặt giá trị này thành false.

public void onResume() { wasShaken = false; } 

trong trình nghe onShake, kiểm tra xem đó có đúng không. nếu có, hãy trở về sớm. Sau đó đặt nó thành 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); 
    } 
}); 
+0

chính xác những gì tôi cần, cảm ơn! :) – Carnivoris

63

Set ý thêm (với putExtra):

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

Lấy ý thêm:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName"); 
} 
Các vấn đề liên quan