Android实现截屏并保存在相册的功能

代码实现
  • 添加权限(AndroidManifest.xml文件里)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • 实现截屏(Java代码)
/**
 * Created by 周旭 on 2017/4/11.
 * 截屏工具类
 */

public class ScreenShotUtils {
    public static boolean shotScreen(Activity activity) {

        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);

        //获取屏幕截图
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
            fos.flush();
            fos.close();

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            activity.getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,573评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,257评论 4 61
  • 1 经常运动的人的食欲会更好,睡眠也更香,工作更有效率,对同事和家人也往往更有耐心。 运动就是一...
    润一粟阅读 283评论 0 0
  • 自制力非常差,是我的一大缺点。 其实,也很想不明白,明明知道自己的缺点所在,为什么就是不能改正。 我想,最大的原因...
    向着太阳奔跑的石头阅读 144评论 0 0
  • 空气中有什么东西在发酵。 如果想要避免预想出的结果, 那就把东西碾落于源头吧。 已经发生的, 已经发生了。 那么没...
    心里藏着一座城阅读 138评论 0 0