Android分享---調(diào)用系統(tǒng)自帶的分享打開功能

調(diào)用系統(tǒng)的分享功能

        //分享文件時(shí)調(diào)用
        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();
            }
        }

調(diào)用系統(tǒng)的打開功能

 //打開文件時(shí)調(diào)用
        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;
        }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容