Search code examples
javaandroidandroid-activityonpause

Starting new activity does not pause current


in my Code I am calling a new activity but the old one gets not paused

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        float x = event.getX();
        float y = event.getY();
        float[] userCordinates = new float[2];

        userCordinates[0] = x;
        userCordinates[1] = y;
        userSequence.add(userCordinates);
        for (int r = 0; r < copySeq.size(); r++) {
            ImageView iv = (ImageView) (findViewById((Integer) copySeq.get(r)));
            int[] loc = new int[2];
            iv.getLocationOnScreen(loc);
            float xRangeMax = iv.getRight();
            float xRangeMin = iv.getLeft();
            float yRangeMax = iv.getBottom();
            float yRangeMin = iv.getTop();

            Integer point = (Integer)copySeq.get(r);

            if (x <= xRangeMax && x >= xRangeMin
                && y <= yRangeMax && y >= yRangeMin) { 
                if(copyColor.get(r).equals("green")){
                Intent intent = new Intent(this, ChildLevel.class);
    startActivity(intent);
            }
            break;
        }
    }
}

When the new Activity is started this code snip in the current Activity is executed but it should be executed when I am coming back. E.g. this Activity should be paused at exactly in this point.

    if (userSequence.size() >= finalSequence.size()) {
        childLevel=false;
        save();
        check(userSequence);
        touchView.setEnabled(false);
    }
}    
return false;

Could anyone please tell me what I am doing wrong? Thanks!


Solution

  • When you start the ChildLevel Activity, the current one (lets call it MainActivity) is paused (onPause() method is called).

    If you want the second code snippet to be executed when you go back to MainActivity, put that code inside onResume() method in MainActivity

    EDIT: so, you only need to execute that piece of code when you go back to MainActivity from ChildLevel. You need to use startActivityForResult():

    In MainActivity, instead of startActivity(), use startActivityForResult():

    Intent intent = new Intent(this, ChildLevel.class);
    startActivityForResult(i, 123);
    

    Then, in ChildLevel, when you want to go back:

    Intent returnIntent = new Intent();
    setResult(Activity.RESULT_OK, returnIntent);
    finish();
    

    Finally, in MainActivity:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 123) {
            if (resultCode == Activity.RESULT_OK){
                // the code you want to execute
            }
        }
    }