java.lang.ClassCastException:在尝试通过Instagram共享打印屏幕时,无法将byte []强制转换为android.os.Parcelable错误

问题描述 投票:0回答:1

我试图从我的应用程序的当前视图生成打印屏幕并通过Instagram分享其图像,但我收到以下错误...

W / Bundle:关键android.intent.extra.STREAM预期Parcelable但值>是[B.返回了默认值。尝试转换生成的内部异常:java.lang.ClassCastException:byte []无法在android.content.Intent.getParcelableExtra(Intent)的android.os.Bundle.getParcelable(Bundle.java:894)中强制转换为android.os.Parcelable .java:7075)在android.content.Intent.migrateExtraStreamToClipData(Intent.java:9887)

我使用以下功能来共享图像:

    public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) {

        final float densityMultiplier = context.getResources().getDisplayMetrics().density;

        int h= (int) (newHeight*densityMultiplier);
        int w= (int) (h * photo.getWidth()/((double) photo.getHeight()));

        photo=Bitmap.createScaledBitmap(photo, w, h, true);

        return photo;
    }

    private static byte[] getScreenShotByteArray(View view){
        View screenView = view.getRootView();
        screenView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
        Bitmap scaledDownBitmap = scaleDownBitmap(bitmap,20,MyApplication.getAppContext());
        screenView.setDrawingCacheEnabled(false);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        scaledDownBitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
        byte[] byteArray = stream.toByteArray();
        return byteArray;
    }

用户按下insta按钮时会触发上述功能:

insta.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent share = new Intent(Intent.ACTION_SEND);

                // Set the MIME type
                share.setType("image/*");

                //Get view
                View rootView = getWindow().getDecorView().findViewById(android.R.id.content);

                // Add the URI to the Intent.
                share.putExtra(Intent.EXTRA_STREAM, getScreenShotByteArray(rootView));
                share.setPackage("com.instagram.android");

                // Broadcast the Intent.
                startActivity(share);
            }
        });

我该怎么做对吗?

java android android-intent
1个回答
0
投票

引用the documentation for EXTRA_STREAM,其值应为:

内容:包含与Intent关联的数据流的URI,与ACTION_SEND一起使用以提供正在发送的数据。

将图像保存到文件,而不是byte[]。然后,配置FileProvider来提供该文件,并使用FileProvider.getUriForFile()Uri放入你的Intent。在使用addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)之前,一定要在Intent上调用startActivity()

也:

  • 使用具体的MIME类型,而不是通配符。这是你的工作,告诉其他应用程序的MIME类型是这个内容,因为你是选择该类型的人。
  • 请注意,只有一小部分Android用户是Instagram用户,因此如果您执行此代码,您的应用程序将在大多数设备上崩溃,因为这些用户不会安装Instagram。
© www.soinside.com 2019 - 2024. All rights reserved.