Android Memory leak in activity

1.4k views Asked by At

I am testing my application using MAT tool and find that there is memory leak but i could not locate it in the code. Please help me on the same.

//First Activity

package intent.sample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class IntentA extends Activity implements OnClickListener {
    Handler handler = new Handler();
    private Intent i;
    private Button button;

    public void onClick(View src) {
        if (src == (View) button) {
            i = new Intent(this, IntentSampleActivity.class);
            handler.postDelayed(new Runnable() {

                public void run() {
                    startActivity(i);
                }
            }, 20000);
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);
        button = (Button) findViewById(R.id.screen2button);
        button.setOnClickListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        this.finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler = null;
        i = null;
        this.finish();
    }
}

//Second Activity

package intent.sample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class IntentSampleActivity extends Activity implements OnClickListener {

    private Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button) findViewById(R.id.screen1button);
        button.setOnClickListener(this);
    }

    public void onClick(View scr) {
        if (scr == (View) button) {
            Intent ii = new Intent(this, IntentA.class);
            startActivity(ii);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        this.finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.finish();
    }
}

I am creating a new thread and starting an activity. Will this create a new instance of the activity class ?

1

There are 1 answers

0
Prem On BEST ANSWER

In this code, everytime when i launch the activity, a new instance is created. To avoid this, i need to use launch mode in android manifest.xml file for the activity. launch mode can be single task or single instance.

Thanks a lot anyways.