Android-heap:AlertDialog中的图像占用了大量的堆内存并且没有释放它

时间:2013-08-17 19:33:29

标签: android android-imageview android-dialog android-memory

我有一个包含图像的特定片段。点击图像后,我放大图像并在带有标题的对话框中显示。

这一切都很好。

在使用DDMS时,我看到堆内存在打开对话框时大约上升了4Mb,并且在没有释放的情况下关闭它。

因此,这样做几次会占用大量的堆内存。

public class ImageOnClickListener implements OnClickListener {
    String article_title ;
    String article_url;

    public ImageOnClickListener(String imageUrl, String title) {
        article_title = title;
        article_url = imageUrl;
    }
    @Override
    public void onClick(View v) {
        View layout = null;
        AlertDialog.Builder imageDialog = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layout = inflater.inflate(R.layout.image_fragment, null);

        TextView articleTitle = (TextView)layout.findViewById(R.id.image_title);
        articleTitle.setText(article_title);
        articleTitle.setTextSize(MainActivity.fontSize +10);
        articleTitle.setTextColor(getResources().getColor(
                android.R.color.white));

        URL imageUri = null;
        try {
            imageUri = new URL(article_url);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
        Bitmap bitmapImage = null;
        try {
            bitmapImage = BitmapFactory.decodeStream(imageUri.openConnection().getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int width = display.getWidth();  // deprecated
        int height = display.getHeight();  

        int w = (int) (width*0.8);
        int h = (int) (height*0.8);

        ImageView imageObject = (ImageView)layout.findViewById(R.id.image_main);
        int imgWidth = bitmapImage.getWidth();
        int imgHeight = bitmapImage.getHeight();
        int ratio = w/imgWidth;

        Bitmap.createScaledBitmap(bitmapImage, imgWidth*ratio,imgHeight*ratio, true);
        imageObject.setImageBitmap(bitmapImage);

        RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(w,h);
        imageObject.setLayoutParams(imageParams);

        alertDialog = imageDialog.setView(layout).create();
        int dialogWidth = (int) (width*0.9);
        int dialogHeight = (int) (height*0.9);
        alertDialog.show();
        alertDialog.getWindow().setLayout(dialogWidth,dialogHeight);


    }
}

基本上我一直在寻找一种方法来解放对话框来释放内存。

0 个答案:

没有答案