Nick
Nick

Reputation: 2948

Situation when a memory leak happens Android

I want to understand when a memory leak happens. For instance if i run this runnable in the activity, all the activity's context will be capture and if a rotation happens, the activity wont get released until the runnable terminates.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    executors.diskIO().execute(new Runnable() {
        @Override
        public void run() {     

                        //CODE HERE

            });
        }
    });
}
}

Lets say i put the runnable inside a class in a seperate file not within the MainActivity and initiate it from the activity. When a rotation happens, is there a memory leak in this case?. I mean the runnable captures the data in every rotation right?

  public class A{

  Data ....


  public A() {}

  functionB(){

       executors.diskIO().execute(new Runnable() {
        @Override
        public void run() { }
         });

    });

   }
 }

Upvotes: 0

Views: 121

Answers (1)

Suhaib Roomy
Suhaib Roomy

Reputation: 2600

Whenever you make an innerclass, it retains the reference of the outer class. If your runnable is inside an activity it will retain an instance to the activity and hence will result in memory leak whereas if you put it in class A it will hold reference of class A not of your activity

If you don't want to access members of the enclosing class it is preferable to make your class static as it wont hold the object of enclosing class.

Upvotes: 2

Related Questions