I created an app that goes to the second page from the first page on shake. But from the second page, it does not come back to the first page. How can I stop the shake activity of the first page when it is closed?
I have implemented onShake()
method in both the pages.
This is the main Activity:
public class MainActivity extends AppCompatActivity implements ShakeDetector.Listener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t= (TextView) findViewById(R.id.t1);
t.setText("Hello World");
SensorManager SM=(SensorManager)getSystemService(SENSOR_SERVICE);
ShakeDetector SD=new ShakeDetector(this);
SD.start(SM);
}
@Override
public void hearShake() {
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
OpenActivityNew();
}
private void OpenActivityNew() {
Intent intent=new Intent(this,TimeDone.class);
finish();
startActivity(intent);
}
}
This is the second Activity:
public class TimeDone extends AppCompatActivity implements ShakeDetector.Listener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer_layout);
TextView t= (TextView) findViewById(R.id.t2);
t.setText("This is Second Page");
SensorManager SM=(SensorManager)getSystemService(SENSOR_SERVICE);
ShakeDetector SD=new ShakeDetector(this);
SD.start(SM);
}
@Override
public void hearShake() {
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
OpenActivityNew();
}
private void OpenActivityNew() {
Intent intent=new Intent(this,MainActivity.class);
finish();
startActivity(intent);
}
I have implemented the same for both classes so that shaking from one page will take to the other and vice versa. But it is only working from MainActivity
.
As I can see in your code, you started your ShakeDetector
inside onCreate()
in both of the Activities but didn't stop it. So you need to stop it before starting another Activity, inside your OpenActivityNew()
, like this:
SD.stopShakeDetector(getBaseContext());
To do this, of course, you need to declare both of the SensorManager SM
and ShakeDetector SD
outside the onCreate()
. Just put them outside as Class variable and that should work fine like this:
MainActivity
:
public class MainActivity extends AppCompatActivity implements ShakeDetector.Listener {
private ShakeDetector SD;
private SensorManager SM;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
SM=(SensorManager)getSystemService(SENSOR_SERVICE);
SD=new ShakeDetector(this);
...
}
...
private void OpenActivityNew() {
SD.stopShakeDetector(getBaseContext());
Intent intent=new Intent(this,TimeDone.class);
finish();
startActivity(intent);
}