Android分享---调用系统自带的分享打开功能

调用系统的分享功能

        //分享文件时调用
        public static void shareFiles(String filesPath) {

            Uri uri = Uri.parse("file://" + filesPath);
            Intent intent = new Intent();
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = GenericFileProvider.getUriForFile(App.getContext(), "org.test.provider.GenericFileProvider", new File(filesPath));
                    intent.setDataAndType(contentUri, getMIMEType(filesPath));
                } else {
                    intent.setDataAndType(uri, getMIMEType(filesPath));
                }
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, uri);

                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                App.getContext().startActivity(Intent.createChooser(intent, "分享"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

调用系统的打开功能

 //打开文件时调用
        public static void openFiles(String filesPath) {

            Uri uri = Uri.parse("file://" + filesPath);
            Intent intent = new Intent();
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    Uri contentUri = GenericFileProvider.getUriForFile(App.getContext(), "org.test.provider.GenericFileProvider", new File(filesPath));
                    intent.setDataAndType(contentUri, getMIMEType(filesPath));
                } else {
                    intent.setDataAndType(uri, getMIMEType(filesPath));
                }

                intent.setAction(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                App.getContext().startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public static String getMIMEType(String filePath) {
            File file = new File(filePath);
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1);
            String type = mime.getMimeTypeFromExtension(ext);

            return type;
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。