在 Android 中与文件路径共享文件/从文件路径获取工作 uri

问题描述

我正在尝试使用以下方法与其他应用(例如 Telegram、Whatapp 等)共享文件

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM,uri);
sendIntent.setType("text/plain");
startActivity(sendIntent);

如果 uri 来自 ACTION_GET_CONTENT 活动,则它有效。但是我只有一个我想共享的文件的路径,如果我设置了:

uri = Uri.fromFile(new File(path))

看起来一切正常,但文件没有在最后一步发送。

如何从文件路径中获取可用的 uri?

解决方法

希望此代码对您有所帮助!

 ApplicationInfo api = getApplicationContext().getApplicationInfo();
                    String apkPath = api.sourceDir;
                    Intent share = new Intent(Intent.ACTION_SEND);
                    share.setType("application/vnd.android.package-archive");
                    share.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(new File(apkPath)));
                    startActivity(Intent.createChooser(share,"Share Via"));