java.lang.ClassCastException:java.io.File无法强制转换为android.os.Parcelable

Анд*_*чук 2 serialization android file android-sharing

我正在尝试创建文本文件共享它(通过蓝牙,电子邮件..)

File file = null;
try {
    file = createFile2(json);
} catch (IOException e) {
    e.printStackTrace();
}

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, file);
shareIntent.setType(getString(R.string.share_contact_type_intent));
Run Code Online (Sandbox Code Playgroud)

这是createFile2()的乐趣:

 public File createFile2(String text) throws IOException {
        File file = new
                File(getFilesDir() + File.separator + "MyFile.txt");

        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
        bufferedWriter.write(text);
        bufferedWriter.close();
        return file;
    }
Run Code Online (Sandbox Code Playgroud)

logcat的:

Bundle? Key android.intent.extra.STREAM expected Parcelable but value was a java.io.File.  The default value <null> was returned.
Bundle? Attempt to cast generated internal exception:
    java.lang.ClassCastException: java.io.File cannot be cast to android.os.Parcelable
            at android.os.Bundle.getParcelable(Bundle.java:1212)
            at android.content.Intent.getParcelableExtra(Intent.java:4652)
            at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7235)
            at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7219)
            at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
            at android.app.Activity.startActivityForResult(Activity.java:3424)
            at android.app.Activity.startActivityForResult(Activity.java:3385)
Run Code Online (Sandbox Code Playgroud)

mat*_*ash 5

填写EXTRA_STREAMfor ACTION_SEND意图时,必须提供Uri资源,而不是File对象本身.

至于异常:虽然通常你可以将一个File对象作为扩展数据的一部分Intent(因为它实现Serializable),接收器需要一个Parcelable实例EXTRA_STREAM,而File不是.

  • 我想你的意思是 `android.net.Uri`,它是一个 `Parcelable` 而不是 `java.net.URI` (2认同)