美文网首页
ScreenShotUtils--Android实现截屏并保存在

ScreenShotUtils--Android实现截屏并保存在

作者: 颤抖的闪电 | 来源:发表于2019-05-18 09:57 被阅读0次
  • 添加权限(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实现截屏并保存在相册的功能

相关文章

网友评论

      本文标题:ScreenShotUtils--Android实现截屏并保存在

      本文链接:https://www.haomeiwen.com/subject/qjmzaqtx.html