将图像文件发送到广播接收器

Sending an image file to a broadcast receiver

我想使用 intent 将图像文件传递给另一个广播接收器,因为 Android 文档建议传递数据值而不是文件。

我怎样才能做到这一点。

为了将图像文件传递给 Android 广播接收器,您必须将文件转换为字节数组并使用 putExtra 方法发送

intent.putExtra("myImage", convertBitmapToByteArray(bitmapImage));

byte[] convertBitmapToByteArray(Bitmap bitmap) {
    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
                Log.e(BitmapUtils.class.getSimpleName(), "ByteArrayOutputStream was not closed");
            }
        }
    }
}

然后你可以在你的广播接收器中转换回图像

byte[] byteArray = intent.getByteArrayExtra("myImage");

Bitmap myImage = convertCompressedByteArrayToBitmap(byteArray);

Bitmap convertCompressedByteArrayToBitmap(byte[] src) {
    return BitmapFactory.decodeByteArray(src, 0, src.length);
}