前言:最近接手的项目 分享系统一塌糊涂,一个视频应用竟然只能分享图片?由于客户一直抱怨,查阅代码后,发现引导了好多第三方分享SDK,我全给删了,因为没必要。
Uri和FileProvider
分享就是告知 第三方应用一个Uri 这个Uri可以是视频,图片或者文件。
然后我们使用 Intent 将这个Uri 告知需要分享的第三方应用。
Uri和FileProvider 相关知识 不懂的请自行查阅 这里不赘述。
这里只讲一个Path转Uri的方法
//Uri 转换
Uri fileUri;
File file = new File(filePath);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
fileUri = FileProvider.getUriForFile(this, "你的应用的包名" + ".fileProvider", file);
} else {
fileUri = Uri.fromFile(file);
}
Intent
这里的Intent 也就是意图 。
当我构造一个意图结构体,向系统发送这个个意图,满足我条件的应用都可以响应这个意图。
具体代码如下
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory("android.intent.category.DEFAULT");
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.setType("video/*");//这里标记为视频 因为我要分享一个视频 其他类型参考下边
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//授权第三方APP可以访问当前的文件
startActivity(Intent.createChooser(intent, "Share Intent"));
如果你需要指定某个应用 你只需要指定包名 即可
intent.setPackage("第三方应用包名");
各种文件类型 你是什么文件 选择响应的类型即可
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".prop", "text/plain"},
{".rar", "application/x-rar-compressed"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
{".xml", "text/xml"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/zip"},
{"", "*/*"}
效果图