2

I didn't quite understand how starting a new activity works and how to release memory when doing that.

This is what i have :

    Button b1, b2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        setContentView(R.layout.activity_main);

        setReferences();
    }

    private void setReferences() {
        b1= (Button) findViewById(R.id.b1);
        b2= (Button) findViewById(R.id.b2);
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent newActivity;
        switch (v.getId()) {
            case R.id.b1:
                newActivity = new Intent("com.sblasblasbla.PLAYACTIVITY");
                startActivity(newActivity);
                break;
            case R.id.b2:
                newActivity = new Intent("com.sdasdsadsa.THIRDACTIVITY");
                startActivity(newActivity);
                break;
        }
    }
}

But when i go to another activity i want to release memory, and if i press the back button(return) from phone to save my activity layout (with background and buttons etc) i mean not to delete them

How can i do that efficiently ? I've heard something with onStop and onDestroy, but i don't know how they work. Also if i destroy activity, it calls again onCreate?

cristi.gherghina
  • 311
  • 1
  • 6
  • 18

2 Answers2

0

There is nothing you need to specifically do to release memory. Android system will automatically garbage collect objects which are no longer needed.

This depends upon several factors like, no. of apps currently running, amount of RAM available, etc. But still give this post a good read.

Aritra Roy
  • 15,355
  • 10
  • 73
  • 107
  • i have also a background image and it is remaining in memory. how to release that because i have 12 MB in heap .. – cristi.gherghina Jul 12 '15 at 16:14
  • You cannot control what should be in the memory and what not. If the system falls short of memory, it will automatically clear off the objects. Just ensure that they are referenced anywhere else. – Aritra Roy Jul 12 '15 at 16:35
0

Unless you leak a pointer to the activity in a static variable, a service or Application, Android will take care of releasing the memory automatically whenever it needs it. This may be just when you leave the activity or it may be later (including never). You may check this article for further information.

To save and restore your activity state (not layout, that does not need saving and is restored with setContentView), you can use onSaveInstanceState and onRestoreInstanceState.

StenSoft
  • 9,369
  • 25
  • 30