如何减少内存泄漏

时间:2014-05-06 14:51:02

标签: android memory-leaks bitmap

我知道这里有很多问题,但我似乎无法理解,因为我对这个记忆问题不熟悉。我有一个应用程序,允许用户从图库中选择图片或拍照,然后让他们添加评论。在一个页面中我想要至少有10张图片,但此时我只能有3张。有人可以帮我这个。我需要一步一步的代码来帮助我减少内存不足。请参阅下面的代码。

用户点击添加图片的按钮。

      private void imgoption() {
    // TODO Auto-generated method stub
    CharSequence[] names = { "From Gallery", "From Camera" };
    new AlertDialog.Builder(context)
            .setTitle("Select an option for updating your Profile Picture")
          .setItems(names, new DialogInterface.OnClickListener() {

            @Override
                public void onClick(DialogInterface dialog, int pos) {
                    // TODO Auto-generated method stub
                    if (pos == 0) {

                        Intent i = new Intent(
                                Intent.ACTION_PICK,
                           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);    


                        startActivityForResult(i, GET_GAL_IMG);


                    } else {


                       Intent i = new Intent(
                                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(i, GET_CAM_IMG);

                    }}}


            )
            .setNegativeButton(android.R.string.cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                        }
                    }).create().show();
         }

之后,这就是我在这里,用户从图库或相机中选择图片,然后这是从转换URI到位图然后调整位图大小的方式。我尝试过使用ByteArrayOutStram但它似乎没有效果(主要是因为我不确定它是如何工作的)。从其他帖子我听说最好使用inSample大小,但我没有正确的方法来实现(不知道在哪里包含该代码或如何)

   @Override
    public void onActivityResult(int requestCode, int resultCode,  Intent intent) {
       super.onActivityResult(requestCode, resultCode, intent);
       switch (requestCode) {

       case 2://Camera
            Log.d("take","pic");
                if (resultCode == -1) {
            String encodedImageString = null;      
            Uri selectimage=intent.getData();    
            String selectedImagepath = getPath(selectimage);                            

          //Changing URI to Bitmap
            Bitmap bmp = null;
            try {

      bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectimage));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }


            //Reducing Memory
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos)) {
                byte[] image = baos.toByteArray();
                encodedImageString = Base64.encodeToString(image,
                        Base64.DEFAULT);
            } else {
                System.out.println("Compression returned false");
                Log.d("Compress", "Compression returned false");
            }


            //Resizing Bitmap
            Bitmap resizedBitmap = Bitmap.createScaledBitmap(bmp, 550, 488, false);
            if(bmp!=resizedBitmap){
                bmp.recycle();
                bmp=null;}


            //Getting INT to find out which IMG button is pressed               
            Intent start=getIntent();               
            pic=(int) start.getIntExtra("pic",pic);

            if(pic==1){
                Log.d("CAMERAPIC","1");
                 tableRow8.setVisibility(View.GONE);
                  tableRow9.setVisibility(View.GONE);
                  tableRow10.setVisibility(View.GONE);
                  tableRow12.setVisibility(View.GONE);
                  tableRow13.setVisibility(View.GONE);
                  tableRow14.setVisibility(View.GONE);
                  add2.setVisibility(View.GONE);
                ImageView img1=(ImageView)findViewById(R.id.img1);
                img1.setImageBitmap(resizedBitmap);

            }

            else if (pic==2){
                Log.d("CAMERAPIC","2");                 
                Button add1=(Button)findViewById(R.id.add1);
                add1.setVisibility(View.GONE);

                 img2=(ImageView)findViewById(R.id.img2);
                 img2.setImageBitmap(resizedBitmap);

                 }

        else if (pic==3){
            Log.d("CAMERAPIC","3");
            Button add2;
            add2=(Button)findViewById(R.id.add2);
            add1.setVisibility(View.GONE);
            add2.setVisibility(View.GONE);

             img3=(ImageView)findViewById(R.id.img3);
             img3.setImageBitmap(resizedBitmap);

         }



        break;}
    case 1://Selecting from Gallery
        Log.d("view","pic");
        if (resultCode == -1) {

            String encodedImageString = null;
             Uri selectimage = intent.getData();
             String selectedImagepath = getPath(selectimage);


       //Changing URI to Bitmap
        Bitmap bmp = null;
        try {

       bmp =BitmapFactory.decodeStream(getContentResolver().openInputStream(selectimage));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


         //Reducing Memory
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos)) {
            byte[] image = baos.toByteArray();
            encodedImageString = Base64.encodeToString(image,
                    Base64.DEFAULT);
        } else {
            System.out.println("Compression returned false");
            Log.d("Compress", "Compression returned false");
        }


        //Resizing Bitmap
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(bmp, 550, 488, false);   
        if(bmp!=resizedBitmap){
            bmp.recycle();
            bmp=null;}



                Log.d("view","picture");

           Intent start=getIntent();
                pic=(int) start.getIntExtra("pic",pic);

                if(pic==1){
                    Log.d("Gallery","1");
                    ImageView img1=(ImageView)findViewById(R.id.img1);
                    img1.setImageBitmap(resizedBitmap);

                    }

                else if (pic==2){
                    Log.d("Gallery","2");
                     Button add1;
                    add1=(Button)findViewById(R.id.add1);
                    add1.setVisibility(View.GONE);

                     img2=(ImageView)findViewById(R.id.img2);
                     img2.setImageBitmap(resizedBitmap);

                        }

            else if (pic==3){
                Log.d("Gallery","3");
                Button add2;
                add2=(Button)findViewById(R.id.add2);
                add2.setVisibility(View.GONE);

                 img3=(ImageView)findViewById(R.id.img3);
                 img3.setImageBitmap(resizedBitmap);

        }
        break;}
        }

}





private String getPath(Uri selectedImage) {
     String[] filePathColumn = { MediaStore.Images.Media.DATA };
     Cursor cursor = context.getContentResolver().query(
             selectedImage, filePathColumn, null, null, null);
     cursor.moveToFirst();
     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
     String filePath = cursor.getString(columnIndex);
     cursor.close();

  //sharedPreference is called userprofile = getting sharedpreference from filename
   (see above)
    SharedPreferences userprofile = getSharedPreferences(filename,0);
    //SHaredPreference Class ->calling Editor --> naming Editor-->
            accessing the sharedpreference name to call the sharedpreference file
    SharedPreferences.Editor editor = userprofile.edit();

    Intent start=getIntent();
    pic=(int) start.getIntExtra("pic",pic);

if(pic==1){
    //Editor->put text of edittext(variable) to save it 
    editor.putString("picpath1", filePath);
   }else if
   (pic==2){
    editor.putString("picpath2", filePath);
        }else if
    (pic==3){
    editor.putString("picpath3", filePath);

   }
    Log.d("saved","done");
    editor.commit();

    return null;
       }

请帮我解决这个问题。我现在搜索这个答案超过一个月了,找不到它。因为我是新手,所以会非常欣赏一步一步的指导。谢谢你

1 个答案:

答案 0 :(得分:0)

内存泄漏的一个原因可能是您的流处理:

你正在打开很多流,但我现在看到了关闭它们的代码。

 bmp = BitmapFactory.decodeStream(
    getContentResolver().openInputStream(selectimage));

 ByteArrayOutputStream baos = new ByteArrayOutputStream();