Android截屏分享工具类,默认截取当前页面

主要实现点击按钮之后,截取App当前的页面,保存到SD卡并且调用系统分享功能,把图片分享出去,废话不多说直接上源码

package com.hyx.keefit.util;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.util.LruCache;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by Administrator on 2017/4/13 0013.
 */

public class ShareUtil {
    private static Bitmap bmp=null;
    private static String imagePath;

    public static void shotRecyclerView(RecyclerView view) {
        RecyclerView.Adapter adapter = view.getAdapter();
        if (adapter != null) {
            int size = adapter.getItemCount();
            int height = 0;
            Paint paint = new Paint();
            int iHeight = 0;
            final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

            // Use 1/8th of the available memory for this memory cache.
            final int cacheSize = maxMemory / 8;
            LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
            for (int i = 0; i < size; i++) {
                RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
                adapter.onBindViewHolder(holder, i);
                holder.itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),
                        holder.itemView.getMeasuredHeight());
                holder.itemView.setDrawingCacheEnabled(true);
                holder.itemView.buildDrawingCache();
                Bitmap drawingCache = holder.itemView.getDrawingCache();
                if (drawingCache != null) {

                    bitmaCache.put(String.valueOf(i), drawingCache);
                }
                height += holder.itemView.getMeasuredHeight();
            }

            bmp = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
            Canvas bigCanvas = new Canvas(bmp);
            Drawable lBackground = view.getBackground();
            if (lBackground instanceof ColorDrawable) {
                ColorDrawable lColorDrawable = (ColorDrawable) lBackground;
                int lColor = lColorDrawable.getColor();
                bigCanvas.drawColor(lColor);
            }

            for (int i = 0; i < size; i++) {
                Bitmap bitmap = bitmaCache.get(String.valueOf(i));
                try{
                    bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint);
                    iHeight += bitmap.getHeight();
                    bitmap.recycle();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if (bmp != null) {
            try {
                //这里是SD卡存储
                // 获取内置SD卡路径
                String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                // 图片文件路径
                String filePath = sdCardPath + File.separator + "screenshot.png";
                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                //这里是内部存储
                //String filePath ="screenshot.png";
                //FileOutputStream os = openFileOutput(filePath,MODE_PRIVATE);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
            } catch (Exception e) {
                //e.printStackTrace();
                //Toast.makeText(MainActivity.this,"haha",Toast.LENGTH_LONG).show();
            }
        }
    }

    public static void screenshot(Activity activity) {
        // 获取屏幕,这4句代码就可以获取屏幕截图
        View dView = activity.getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        bmp = dView.getDrawingCache();
        if (bmp != null) {
            try {
                //这里是SD卡存储
                // 获取内置SD卡路径
                String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                // 图片文件路径
                String filePath = sdCardPath + File.separator + "screenshot.png";
                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                //这里是内部存储
                //String filePath ="screenshot.png";
                //FileOutputStream os = openFileOutput(filePath,MODE_PRIVATE);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
            } catch (Exception e) {
                //e.printStackTrace();
                //Toast.makeText(MainActivity.this,"haha",Toast.LENGTH_LONG).show();
            }
        }
    }

    //分享单张图片
    public static void shareSingleImage(Activity activity) {
        imagePath = Environment.getExternalStorageDirectory() + File.separator + "screenshot.png";

        //由文件得到uri
        Uri imageUri = Uri.fromFile(new File(imagePath));
        //Log.d("share", "uri:" + imageUri);  //输出:file:///storage/emulated/0/test.jpg
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shareIntent.setType("image/*");
        //这里主要是有选择的选取分享应用,比如过滤蓝牙之类的,但是过滤之后有BUG,目前还没有写出来,如果不需要过滤那么这一段过滤掉
        /*
        String contentDetails = "";
        String contentBrief = "";
        String shareUrl = "";
        List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(shareIntent, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
        for (int n = 0; n < resInfo.size(); n++) {
            Log.i("zsy", resInfo.get(n).activityInfo.name + "");
        }

        if (!resInfo.isEmpty()) {
            List<Intent> targetedShareIntents = new ArrayList<Intent>();
            HashMap<String, Intent> targetedShareIntentss = new HashMap<String, Intent>();
            for (ResolveInfo info : resInfo) {
                Intent targeted = new Intent(Intent.ACTION_SEND);
                targeted.setType("image/*");
                ActivityInfo activityInfo = info.activityInfo;

                //Log.i("zsy",activityInfo.packageName);
                Log.i("zsy", activityInfo.name);
                // judgments : activityInfo.packageName, activityInfo.name, etc.
                //这里是进行过滤的方法,根据需要添加
                if (activityInfo.packageName.contains("bluetooth") ||activityInfo.name.contains("bluetooth")) {

                    continue;
                }
                targeted.setPackage(activityInfo.packageName);
                //targeted.setData(Uri.parse(activityInfo.targetActivity));
                targeted.setClassName(activityInfo.packageName, activityInfo.name);
                targetedShareIntents.add(targeted);
                targetedShareIntentss.put(activityInfo.packageName, targeted);
            }

            ArrayList<Intent> result = new ArrayList<Intent>();
            Iterator it = targetedShareIntentss.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (java.util.Map.Entry) it.next();
                result.add((Intent) entry.getValue());
            }
            Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");
            if (chooserIntent == null) {
                return;
            }
            // A Parcelable[] of Intent or LabeledIntent objects as set with
            // putExtra(String, Parcelable[]) of additional activities to place
            // a the front of the list of choices, when shown to the user with a
            // ACTION_CHOOSER.


            try {
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
                startActivity(chooserIntent);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(this, "Can't find share component to share", Toast.LENGTH_SHORT).show();
            }
        }*/

        //这里是要修改的

        Intent chooserIntent =Intent.createChooser(shareIntent,"分享到");
        if(chooserIntent ==null){
            return;
        }
        try{
            activity.startActivity(chooserIntent);
        }catch(android.content.ActivityNotFoundException ex){
            Toast.makeText(activity,"Can't find share component to share",Toast.LENGTH_SHORT).show();
        }
        //startActivity(Intent.createChooser(shareIntent, "分享到"));

    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值