Android基础 -- Activity之间传递数据(bitmap和map对象)

本文深入探讨了Android应用中数据传递的多种方式,包括HashMap、Bitmap等复杂数据类型的处理技巧,特别关注图片数据的高效传递,提供了实用的代码示例。

第一,传递HashMap对象

 HashMap本身已经实现了Cloneable, Serializable,Intent传递时,直接强转就可以了。

Map<String, String> params = new HashMap<>();
params.put("key", "value");
 
Intent intent = new Intent(app, Activity.class);
intent.putExtra("parmas",(Serializable)params);

2. 传递Bitmap

强调一遍一定不要通过Intent传

2.1 本地资源只传递R.id,然后通过resource去解析出来;

2.2 如果是SDCard中的文件,只传递Uri;

2.3 如果是网络流,先本地保存图片,然后再传递路径Uri。

另,Intent可传递的数据大小有限,具体多少我并未实际测试过,跟ROOM设置的APP最大内存也有关系,网上有人做了实际代码测试,地址:https://blog.youkuaiyun.com/wingichoy/article/details/50679322

=========================================

1)直接传递bitmap

直接传递有2中。一种是putExtra(),一种是转换为byte流。 
putExtra: http://www.jb51.net/article/40747.htm\

Byte流: http://blog.youkuaiyun.com/jdsjlzx/article/details/8362967

前者要简便些。二者都有同样的限制:图片太大时,测试时就显示不了。

(2)传递图片的uri

这个思路相对麻烦些。要先把bitmap流转换成uri类资源。事实是,中间还有过程。 
我不知道安卓系统有没有直接把bitmap流转换成uri类资源方法。我的处理是先将bitmap流转换为文件,再转换成uri类资源。

Bitmap转换成File:

public String saveBitmap(Bitmap mBitmap) {
        File file = new File(FILE_DIR);   //FILE_DIR自定义
        if (!file.exists()) {
            file.mkdir();
        }
        File tmpf = new File(file, setFileName() + ".jpg");
        File f = tmpf;
        try {
            f.createNewFile();
            FileOutputStream fOut = null;
            fOut = new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);        
            fOut.flush();
            fOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String image_file_url=f.getAbsolutePath();
        Log.i("image_file_url", image_file_url);
        return image_file_url;
    }

获取文件的路径很重要。getAbsolutePath()是这类方法。 
接下来,

Uri imageUri = Uri.parse(saveBitmap(bitmap));
    intent.setData(imageUri);
    startActivity(intent);

另一个activity中,还要把uri中的资源还原到bitmap:

//获取Uri中的bitmap
    private Bitmap getBitmapFromUri(Uri uri)
    {
        try
        {
            // 读取uri资源中的bitmap
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            return bitmap;
        }
        catch (Exception e)
        {
            Log.e("[Android]", e.getMessage());
            Log.e("[Android]", "目录为:" + uri);
            e.printStackTrace();
            return null;
        }
    }   

    //将Uri中图片相关数据转换成bitmap  
    private void Uri_to_bitmap(ImageView imageView) {           
        Intent intent = getIntent();
        if(intent != null){
            Uri uri = intent.getData();
            if (uri == null) {
                Log.i("tag", "The uri is not exist.");
                return;     
            }
            intent.setDataAndType(uri, "image/*");
            Bundle extras = intent.getExtras();     
            if (extras != null) {
                Bitmap photo = extras.getParcelable("intent");
                imageView.setImageBitmap(photo);    
            }else{
                Log.i("extras", "The extras is null.");
            }
        }else{
            Log.i("intent", "The intent is null.");
        }       
    }

一般将相机或图库中图片uri对应的bitmap取出,

// 读取uri资源中的bitmap
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

如果你自定义的文件路径太偏僻了,用该方法可能无效。只能用这种方式:

Uri uri = Uri.fromFile(image_file);//image_file是File型

这里又回到获取文件路径的问题。这里的getBitmap()也有个问题:也会受限于图片过大。因此,对过大图片,时时注意释放缓存。

而且,还要针对安卓不同版本处理。

(3)传递图片的url

private Bitmap getBitmap(String path){
        //先解析图片边框的大小
        BitmapFactory.Options ops = new BitmapFactory.Options();
        ops.inJustDecodeBounds = true;
        Bitmap bm = BitmapFactory.decodeFile(path, ops);
        ops.inSampleSize = 1;
        int oHeight = ops.outHeight;
        int oWidth = ops.outWidth;
        //控制压缩比
        int contentHeight = 0;
        int contentWidth = 0;
        contentHeight = ITEM_HEIGHT; //自定义
        contentWidth = ITEM_WIDTH;   //自定义
        if(((float)oHeight/contentHeight) < ((float)oWidth/contentWidth)){
             ops.inSampleSize = (int) Math.ceil((float)oWidth/contentWidth);
        }else{
             ops.inSampleSize = (int) Math.ceil((float)oHeight/contentHeight);
        }
             ops.inJustDecodeBounds = false;
             bm = BitmapFactory.decodeFile(path, ops);
        return bm;
    }

onCreate()中添加:

        String img_url = getIntent().getStringExtra("img_url");     
        imgV.setImageBitmap(getBitmap(img_url));


以上是3种方式的demo。其中,困扰我比较久的有获取自定义文件路径、bitmap资源与uri之间的转换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值