1. 程式人生 > >android 獲取螢幕截圖並呼叫系統分享

android 獲取螢幕截圖並呼叫系統分享

呼叫的系統自帶的分享而不是接入的第三方sdk
第一步:
獲取螢幕截圖

 // 獲取螢幕(包括導航
View dView =AddressDetailsActivity.this.getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
//        // 獲取螢幕(不包括導航
//        View dView = getWindow().getDecorView
(); // dView.setDrawingCacheEnabled(true); // dView.buildDrawingCache(); // Bitmap bmp = Bitmap.createBitmap(dView.getDrawingCache()); if (bmp != null) { try { // 獲取內建SD卡路徑 String sdCardPath = Environment.getExternalStorageDirectory().getPath
(); // 圖片檔案路徑 imagePath = sdCardPath + File.separator + "test.png"; File file = new File(imagePath); FileOutputStream os = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.PNG, 100, os); os.flush
(); os.close(); } catch (Exception e) { } }

第二步:判斷是否儲存成功,成功即呼叫分享

        if (imagePath != null){
                    Intent intentz = new Intent(Intent.ACTION_SEND); // 啟動分享傳送的屬性
                    File file = new File(imagePath);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                        Uri contentUri = FileProvider.getUriForFile(getApplication(), "xxxx.fileprovider", file);// xxx修改為自己專案的
                        intentz.putExtra(Intent.EXTRA_STREAM, contentUri);
                    }else {
                        intentz.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));// 分享的內容
                    }
                    intentz.setType("image/*");// 分享傳送的資料型別
                    Intent chooser = Intent.createChooser(intentz, "Share screen shot");
                    if(intentz.resolveActivity(getPackageManager()) != null){
                        startActivity(chooser);
                    }

                }

ps:需要注意的也就是系統版本fileprovider 需要進行適配