如何在android中释放堆内存

时间:2014-03-21 07:05:39

标签: java android

我想开发一个列表视图,其中包含此代码完成的图像和文本视图   完美,但我的代码分配了大量的堆内存,它没有释放内存。   我在ondestroy中初始化了所有空值,但它对我没有任何作用。

帮助我任何一个我坚持这个......

public class EventsActivity extends Activity implements OnClickListener {
private ListView mListview;
private EventsAdapter adapter;
InitialRequestResponseDto mInitialRequestResponseDto;
Context mContext;
private ImageButton mPlayButton;
//private ImageButton mRepeatButton;
private ImageButton mNextButton;
private ImageButton mPreviousButton;
//private ImageButton mStopButton;
TextView title, descrip;
ImageView songIcon;
boolean mBroadcastIsRegistered;
Intent intent, serIntent;
static ProgressDialog mdialog;
LazyImageLoader lazyImageLoader;
private static int songEnded = 0;
private TextView mHeading;
final String SUGGESTED_URL = "http://www.vorbis.com/music/Epoq-Lepidoptera.ogg";
RelativeLayout mRelativeLayout;
private ImageButton mHome;
private ImageButton mFm;
private String langid;
private ImageView mArrow;
Typeface tf,tf2;
private Button mBack;
String mRprgmname;
private TextView mPrgmTxtVw;
private TextView mPrgmName;

private RelativeLayout mrelative;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    setContentView(R.layout.commonsongslist);
    mrelative = (RelativeLayout) findViewById(R.id.Rlplayall);
    title = (TextView) findViewById(R.id.songnamemaint);
    songIcon = (ImageView) findViewById(R.id.cntrylogo);
    mPrgmTxtVw = (TextView) findViewById(R.id.prmnametxt);
    mPrgmName = (TextView) findViewById(R.id.prmname);
    mBack = (Button) findViewById(R.id.backs);
    mHome = (ImageButton) findViewById(R.id.home);
    mRelativeLayout = (RelativeLayout) findViewById(R.id.commonlayout);
    mRelativeLayout.setBackgroundColor(Color.rgb(234, 183, 51));
    mListview = (ListView) findViewById(R.id.listsongs);
    mHeading = (TextView) findViewById(R.id.txtheading);
    mPlayButton = (ImageButton) findViewById(R.id.btnPlay);
    mNextButton = (ImageButton) findViewById(R.id.nextbtn);
    mPreviousButton = (ImageButton) findViewById(R.id.prvsbtn);
    mArrow = (ImageView) findViewById(R.id.arrowimage);
    mArrow.setImageResource(R.drawable.events_a);
    mFm = (ImageButton) findViewById(R.id.fmbtn);
    Intent intent = getIntent();
    langid = intent.getStringExtra("languageid");
    lazyImageLoader = new LazyImageLoader(mContext);
    mHeading.setText("Events");
    DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
    // mHeading.setTextSize(20/ metrics.scaledDensity);
    if (metrics.scaledDensity < 1) {
        mHeading.setTextSize(16);
    } else if (metrics.scaledDensity >= 2) {
        mHeading.setTextSize(16);
    } else if (metrics.scaledDensity >= 1 && metrics.scaledDensity < 2) {
        mHeading.setTextSize(18 / metrics.scaledDensity);
    }
    Typeface tf = Typeface.createFromAsset(this.getAssets(),
            "fonts/Oswald-Bold.ttf");
    mHeading.setTypeface(tf);
    Typeface tf2 = Typeface.createFromAsset(this.getAssets(),
            "fonts/arial.ttf");
    mBack.setTypeface(tf2);
    mBack.setBackgroundResource(R.drawable.events_back);
    mRprgmname = getIntent().getStringExtra("name");

    if (Utills.isNetworkAvailable(mContext)) {

        mPlayButton.setOnClickListener(this);
        mNextButton.setOnClickListener(this);
        mPreviousButton.setOnClickListener(this);
    }
    mBack.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            onBackPressed();
        }
    });
    mHome.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            LanguagesGetAsnchTask task = new LanguagesGetAsnchTask(
                    mContext, Constants.LANGUAGE_URL);
            task.execute();
        }
    });
    mFm.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
    RadioAsynchTask   
     task=newRadioAsynchTask(mContext,Constants.channels,Constants.LANGUAGE_URL, langid,
                    mRprgmname);
            task.execute();
        }
    });
    mInitialRequestResponseDto = (InitialRequestResponseDto) getIntent()
            .getSerializableExtra("events");
    adapter = new EventsAdapter(this, 1, mInitialRequestResponseDto
            .getInitialResposeBean().getEvevtsdto());
    mListview.setAdapter(adapter);
    mListview.invalidate();
    mListview.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
                long arg3) {
            String title = mInitialRequestResponseDto
                .getInitialResposeBean().getEvevtsdto().get(pos)
                    .getEvent_title();
            String image = mInitialRequestResponseDto


                      .getInitialResposeBean().getEvevtsdto().get(pos)
                    .getEvent_poster();
            String desc = mInitialRequestResponseDto

                          .getInitialResposeBean().getEvevtsdto().get(pos)
                    .getLong_desc();
            Intent intent = new Intent(mContext, DetailedEvents.class);
            intent.putExtra("image_path", image);
            intent.putExtra("languageid", langid);
            intent.putExtra("description", desc);
            intent.putExtra("eventtitle", title);
            intent.putExtra("name", mRprgmname);
            startActivity(intent);

        }
    });
}

private void updateUi(Intent serviceIntent) {
    if (songEnded == 1) {
        mPlayButton.setImageResource(R.drawable.play);
        updateUI();
    }
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent serviceIntent) {
        EventsActivity.this.serIntent = serviceIntent;
        if (serviceIntent.getAction().equalsIgnoreCase(
                MusicService.ACTION_STATE_CHANGED)) {
            updateUI();
        }
        if (serviceIntent.getAction().equalsIgnoreCase(
                MusicService.BROADCAST_ACTION)) {
            updateUi(serviceIntent);
        }

        if (serviceIntent.getAction().equalsIgnoreCase(
                MusicService.BROADCAST_BUFFER)) {
            Toast.makeText(context, "Buffering",   
                     Toast.LENGTH_LONG).show();

        }

    }

};

private void updateUI() {

    RadioDto songItem = MusicHolder.getInstance().getCurrentItem();
    State mState = MusicHolder.getInstance().getState();
    if (mState == State.Playing) {
        mPlayButton.setImageResource(R.drawable.pause);
    } else if (mState == State.Paused || mState == State.Stopped) {
        mPlayButton.setImageResource(R.drawable.play);

    }

    if (songItem != null) {
        title.setSelected(true);
        title.setText(songItem.getTitle());
        title.setTypeface(tf2);
        title.setTextColor(Color.rgb(234, 183, 51));
        if (AMP.isAlbumname()) {
            mPrgmTxtVw.setText("Album Name:");
        } else {
            mPrgmTxtVw.setText("Program Name:");
        }
        if (mRprgmname != null) {
            mPrgmName.setText(mRprgmname);
        } else {
            mPrgmName.setText(" ");
        }
        mPrgmName.setSelected(true);
        mPrgmName.setTypeface(tf2);
        mPrgmTxtVw.setTypeface(tf2);
        DisplayMetrics metrics = mContext.getResources()
                .getDisplayMetrics();
        if (metrics.scaledDensity < 1) {
            title.setTextSize(16);
            mPrgmTxtVw.setTextSize(14);
            mPrgmName.setTextSize(14);
        } else if (metrics.scaledDensity >= 2) {
            title.setTextSize(16);
            mPrgmTxtVw.setTextSize(14);
            mPrgmName.setTextSize(14);
            RelativeLayout.LayoutParams params = 
                    (RelativeLayout.LayoutParams) mrelative
                    .getLayoutParams();
            params.setMargins(0, 0, 0, 90); // left, top, right, bottom
            mrelative.setLayoutParams(params);
        } else if (metrics.scaledDensity >= 1 && metrics.scaledDensity < 2)    
            {
            title.setTextSize(18 / metrics.scaledDensity);
            mPrgmName.setTextSize(16 / metrics.scaledDensity);
            mPrgmTxtVw.setTextSize(16 / metrics.scaledDensity);
        }
        if (songItem.getImage() != null) {
            final String url = songItem.getImage();
            songIcon.setTag(url);
            Thread Moviesthread3 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                Bitmap bitmap = Utills.getBitmapFromURL(url);
                    bitmap = Utills.getCircularBitmap(bitmap);
                        songIcon.setImageBitmap(bitmap);
                        bitmap.recycle();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            Moviesthread3.start();
            songIcon.invalidate();
        }

    } else {
        title.setText("Radio Khushi");
        // descrip.setText("select song from playlist");
    }
}

protected void onResume() {
    super.onResume();
    boolean dia = false;
    registerReceiver(broadcastReceiver, new IntentFilter(
            MusicService.ACTION_STATE_CHANGED));
    registerReceiver(broadcastReceiver, new IntentFilter(
            MusicService.BROADCAST_ACTION));
    registerReceiver(broadcastReceiver, new IntentFilter(
            MusicService.BROADCAST_BUFFER));

    mBroadcastIsRegistered = true;

    if (songEnded == 1) {
        mPlayButton.setImageResource(R.drawable.play);
    }

    updateUI();

}

@Override
protected void onPause() {
    super.onPause();
    if (mBroadcastIsRegistered) {
        try {
            unregisterReceiver(broadcastReceiver);
            mBroadcastIsRegistered = false;
        } catch (Exception e) {

            e.printStackTrace();
            Toast.makeText(getApplicationContext(),
                e.getClass().getName() + " " + e.getMessage(),

                    Toast.LENGTH_LONG).show();
        }
    }
}

public void onClick(View target) {
    MusicHolder musicHolder = MusicHolder.getInstance();
    final State mState = musicHolder.getState();
    if (musicHolder.getItems().size() != 0) {
        Intent intent = new Intent(this, MusicService.class);

        if (target == mPlayButton) {
            if (mState == State.Playing && mState != State.Preparing
                    && mState != State.Retrieving) {
                intent.setAction(MusicService.ACTION_PAUSE);
                startService(intent);
        } else if (mState == State.Paused || mState == State.Stopped) {
                intent.setAction(MusicService.ACTION_PLAY);
                startService(intent);
            }
        } else if (target == mNextButton) {

            intent.setAction(MusicService.ACTION_SKIP);
            mNextButton.setBackgroundResource(R.drawable.next_pressed);

            startService(intent);
            String time = "";
            int index = musicHolder.getIndex();
        InitialRequestResponseDto mInitialRequestResponseDto1 = null;

            InitialResposeBean ini = new InitialResposeBean();
            ini.setRadiolist(musicHolder.getItems());
        mInitialRequestResponseDto1 = new InitialRequestResponseDto();
            mInitialRequestResponseDto1.setInitialResposeBean(ini);
            index++;
            if (index == mInitialRequestResponseDto1
                .getInitialResposeBean().getRadiolist().size()) {
                index = 0;
            }
            time = mInitialRequestResponseDto1.getInitialResposeBean()
                    .getRadiolist().get(index).getTime_zone();
            String[] s = time.split(" ");
            TimeZone tz = TimeZone.getTimeZone("GMT" + s[0] + s[1]);
            Calendar c = Calendar.getInstance(tz);
            String caltime = c.get(Calendar.HOUR_OF_DAY) + "."
                    + c.get(Calendar.MINUTE);

            mRprgmname = Utills.getpname1(mInitialRequestResponseDto1,
                    index, caltime, Utills.getdayofweek());

        } else if (target == mPreviousButton) {
            intent.setAction(MusicService.ACTION_REWIND);
        mPreviousButton.setBackgroundResource(R.drawable.prev_pressed);

            startService(intent);
            String time = "";
        InitialRequestResponseDto mInitialRequestResponseDto1 = null;
            int index = musicHolder.getIndex();

            InitialResposeBean ini = new InitialResposeBean();
            ini.setRadiolist(musicHolder.getItems());
        mInitialRequestResponseDto1 = new InitialRequestResponseDto();
            mInitialRequestResponseDto1.setInitialResposeBean(ini);

            index--;
            if (index == -1) {
            index = mInitialRequestResponseDto1.getInitialResposeBean()
                        .getRadiolist().size() - 1;
            }
            time = mInitialRequestResponseDto1.getInitialResposeBean()
                    .getRadiolist().get(index).getTime_zone();

            String[] s = time.split(" ");
            TimeZone tz = TimeZone.getTimeZone("GMT" + s[0] + s[1]);

            Calendar c = Calendar.getInstance(tz);

            String caltime = c.get(Calendar.HOUR_OF_DAY) + "."
                    + c.get(Calendar.MINUTE);

            mRprgmname = Utills.getpname1(mInitialRequestResponseDto1,
                    index, caltime, Utills.getdayofweek());
        }
    } else {
        Toast.makeText(mContext, "No Song In Holder", Toast.LENGTH_LONG)
                .show();
    }
    if (mState == State.Stopped) {
        Toast.makeText(mContext, "No Song In Holder", Toast.LENGTH_LONG)
                .show();
    }
}

protected void onDestroy() {
    super.onDestroy();
    Toast.makeText(mContext, "events ondestroy", Toast.LENGTH_SHORT).show();
    mrelative=null;mPrgmName=null;mPrgmTxtVw=null;
    mBack=null;
    tf=null;
    tf2=null;
    mArrow=null;
    mFm=null;
    mHome=null;
    mRelativeLayout=null;
    mHeading=null;
    lazyImageLoader=null;
    mdialog=null;
    intent=null;
    serIntent=null;
    songIcon=null;
    title=null;
    descrip=null;
    mPreviousButton=null;
    mNextButton=null;
    mPlayButton=null;
    mContext=null;
    mInitialRequestResponseDto=null;
    adapter=null;
    mListview=null;
    System.gc();
}

}

,适配器类是

 package com.onlineradio.adapters;

 import java.util.List;

 import android.content.Context;
 import android.graphics.Typeface;
 import android.util.DisplayMetrics;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ImageView;
 import android.widget.TextView;

 import com.onlineradio.Utils.LazyImageLoader;
 import com.onlineradio.dto.EventsDto;
 import com.siriinnovations.radiokhushi.R;

 public class EventsAdapter extends ArrayAdapter<EventsDto> {
Context mContext;
EventsDto category;
public LazyImageLoader lazyImageLoader;
List<EventsDto> categories;
int selectedLanguage;

public EventsAdapter(Context context, int textViewResourceId,
        List<EventsDto> list) {
    super(context, textViewResourceId, list);
    this.categories = list;
    this.mContext = context;
    lazyImageLoader = new LazyImageLoader(mContext.getApplicationContext());
}

@Override
public int getCount() {
    return categories.size();
}

public EventsDto getItem(int position) {
    return super.getItem(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public static class ViewHolder {
    public TextView mEvntName;
    public ImageView mImage;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View vi = convertView;
    ViewHolder holder;
    category = getItem(position);
    // if (convertView == null) {
    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    vi = inflater.inflate(R.layout.event_row, parent, false);
    holder = new ViewHolder();
    holder.mEvntName = (TextView) vi.findViewById(R.id.eventname);
    holder.mImage = (ImageView) vi.findViewById(R.id.eventimage);
    vi.setTag(holder);
    // } else {
    // holder = (ViewHolder) vi.getTag();
    // }
    String title = categories.get(position).getEvent_title();
    holder.mEvntName.setText(title);
    Typeface tf = Typeface.createFromAsset(mContext.getAssets(),
            "fonts/arial.ttf");
    holder.mEvntName.setTypeface(tf);
    DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
    // holder.mEvntName.setTextSize(15 / metrics.scaledDensity);
    if (metrics.scaledDensity < 1) {
        holder.mEvntName.setTextSize(16);
    } else if (metrics.scaledDensity >= 2) {
        holder.mEvntName.setTextSize(14);
    } else if (metrics.scaledDensity >= 1 && metrics.scaledDensity < 2) {
        holder.mEvntName.setTextSize(18 / metrics.scaledDensity);
    }
    String imageurl = categories.get(position).getEvent_poster();
    // holder.mImage.setImageBitmap(Utills.getBitmapFromURL(imageurl));
    // new DownloadImageTask((ImageView) vi.findViewById(R.id.eventimage))
    // .execute(imageurl);

    // if ((imageurl == null) || imageurl.equalsIgnoreCase("null")) {
    // holder.mImage.setVisibility(ImageView.GONE);
    //
    // } else {
    lazyImageLoader.displayImage(imageurl, holder.mImage,
            R.drawable.ic_launcher);

    // holder.mImage.setLayoutParams(new ViewGroup.LayoutParams(
    // WindowManager.LayoutParams.MATC`enter code here`H_PARENT,
    // WindowManager.LayoutParams.WRAP_CONTENT));
    // holder.mImage.setImageBitmap(Utills.getBitmapFromURL(imageurl));
    holder.mImage.setTag(imageurl);
    // holder.mImage.invalidate();
    return vi;
}

 }

1 个答案:

答案 0 :(得分:0)

使用MAT分析应用的内存使用情况,如this帖子中所述。此工具将帮助您跟踪应用程序使用的内存并发现潜在的内存泄漏。