美文网首页android技术学习之鸿蒙&Android
Android 获取系统截屏回调处理逻辑

Android 获取系统截屏回调处理逻辑

作者: 咚咚_Coding | 来源:发表于2021-07-02 23:21 被阅读0次

    注意点

    1、通常是在onResume(注册)与onPause(销毁),但是系统权限弹框show的时候activity会执行onPause回调,导致setListener为空,截屏回调不了的问题
    2、动态申请读数据库权限制Manifest.permission.READ_EXTERNAL_STORAGE,加在 onChange中校验  
    3、onChange可能会回调多次,截屏后如果串行多个流程,任务进行中需要拦截截屏回调(不让其执行),结束后用户触发截屏动作再允许回调;
      /**
       * @param excuteRequest true 不允许回调
       */
      public synchronized void changeStatus(boolean excuteRequest) {
          if (isExcuteRequest != excuteRequest)
            isExcuteRequest = excuteRequest;
      }
    

    How Use

    在你的Activity初始化方法中注册(或者其他使用到的地方)
    private fun registExcuteShot() {
        if (null == mScreenShotListenManager) {
            mScreenShotListenManager = ScreenShotListenManager.newInstance(this)
        }
        mScreenShotListenManager?.startListen()
        //回调
        mScreenShotListenManager?.setListener {
            processDistanceAndHint()
        }
    }
    
    在你的Activity销毁方法中注册
    private fun stopShot() {
        if (null != mScreenShotListenManager) {
            mScreenShotListenManager?.stopListen()
            mScreenShotListenManager = null
        }
    
    }
    

    All Code

    /**
     * 监听截屏回调
     */
    public class ScreenShotListenManager {
    private static final String TAG = "ScreenShotListenManager";
    
    /**
     * 读取媒体数据库时需要读取的列
     */
    private static final String[] MEDIA_PROJECTIONS = {
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
            MediaStore.Images.ImageColumns.DATE_ADDED
    
    };
    /**
     * 读取媒体数据库时需要读取的列, 其中 WIDTH 和 HEIGHT 字段在 API 16 以后才有
     */
    private static final String[] MEDIA_PROJECTIONS_API_16 = {
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
            MediaStore.Images.ImageColumns.DATE_ADDED,
            MediaStore.Images.ImageColumns.WIDTH,
            MediaStore.Images.ImageColumns.HEIGHT,
    };
    
    /**
     * 截屏依据中的路径判断关键字
     */
    private static final String[] KEYWORDS = {
            "screenshot", "screen_shot", "screen-shot", "screen shot",
            "screencapture", "screen_capture", "screen-capture", "screen capture",
            "screencap", "screen_cap", "screen-cap", "screen cap", "Screenshots", "Screenshot"
    };
    
    private static Point sScreenRealSize;
    
    /**
     * 已回调过的路径
     */
    private final static List<String> sHasCallbackPaths = new ArrayList<String>();
    
    private Context mContext;
    
    private OnScreenShotListener mListener;
    
    private long mStartListenTime;
    
    /**
     * 内部存储器内容观察者
     */
    private MediaContentObserver mInternalObserver;
    
    /**
     * 外部存储器内容观察者
     */
    private MediaContentObserver mExternalObserver;
    
    /**
     * 运行在 UI 线程的 Handler, 用于运行监听器回调
     */
    private final Handler mUiHandler = new Handler(Looper.getMainLooper());
    private static RxPermissions mRxPermissions;
    private boolean isExcuteRequest;
    
    private ScreenShotListenManager(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("The context must not be null.");
        }
        mContext = context;
    
        // 获取屏幕真实的分辨率
        if (sScreenRealSize == null) {
            sScreenRealSize = getRealScreenSize();
            if (sScreenRealSize != null) {
                Log.d(TAG, "Screen Real Size: " + sScreenRealSize.x + " * " + sScreenRealSize.y);
            } else {
                Log.w(TAG, "Get screen real size failed.");
            }
        }
    }
    
    public static ScreenShotListenManager newInstance(AppCompatActivity context) {
        mRxPermissions = new RxPermissions(context);
        assertInMainThread();
        return new ScreenShotListenManager(context);
    }
    
    /**
     * 启动监听
     */
    public void startListen() {
        isExcuteRequest = false;
        assertInMainThread();
    
    //  sHasCallbackPaths.clear();
    
        // 记录开始监听的时间戳
        mStartListenTime = System.currentTimeMillis();
    
        // 创建内容观察者
        mInternalObserver = new MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mUiHandler);
        mExternalObserver = new MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mUiHandler);
    
        //Android Q(10) ContentObserver 不回调 onChange
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
            // 注册内容观察者
            mContext.getContentResolver().registerContentObserver(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                    true,
                    mInternalObserver
            );
            mContext.getContentResolver().registerContentObserver(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    true,
                    mExternalObserver
            );
        } else {
            // 注册内容观察者
            mContext.getContentResolver().registerContentObserver(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                    false,
                    mInternalObserver
            );
            mContext.getContentResolver().registerContentObserver(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    false,
                    mExternalObserver
            );
        }
    }
    
    /**
     * 停止监听
     */
    public void stopListen() {
        isExcuteRequest = false;
        assertInMainThread();
    
        // 注销内容观察者
        if (mInternalObserver != null) {
            try {
                mContext.getContentResolver().unregisterContentObserver(mInternalObserver);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mInternalObserver = null;
        }
        if (mExternalObserver != null) {
            try {
                mContext.getContentResolver().unregisterContentObserver(mExternalObserver);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mExternalObserver = null;
        }
        if (null != mRxPermissions) {
            mRxPermissions = null;
        }
        // 清空数据
        mStartListenTime = 0;
        // sHasCallbackPaths.clear();
    
        //切记!!!:必须设置为空 可能mListener 会隐式持有Activity导致释放不掉
        mListener = null;
        mUiHandler.removeCallbacksAndMessages(null);
    }
    
    /**
     * 处理媒体数据库的内容改变
     */
    private void handleMediaContentChange(Uri contentUri) {
        Cursor cursor = null;
        try {
            // 数据改变时查询数据库中最后加入的一条数据
            cursor = mContext.getContentResolver().query(
                    contentUri,
                    Build.VERSION.SDK_INT < 16 ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,
                    null,
                    null,
                    MediaStore.Images.ImageColumns.DATE_MODIFIED + " desc limit 1"
            );
    
            if (cursor == null) {
                Log.e(TAG, "Deviant logic.");
                return;
            }
            if (!cursor.moveToFirst()) {
                Log.d(TAG, "Cursor no data.");
                return;
            }
    
            // 获取各列的索引
            int dataIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            int dateTakenIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN);
            int widthIndex = -1;
            int heightIndex = -1;
            widthIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.WIDTH);
            heightIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.HEIGHT);
    
            // 获取行数据
            String data = cursor.getString(dataIndex);
            long dateTaken = cursor.getLong(dateTakenIndex);
            int width = 0;
            int height = 0;
            if (widthIndex >= 0 && heightIndex >= 0) {
                width = cursor.getInt(widthIndex);
                height = cursor.getInt(heightIndex);
            } else {
                // API 16 之前, 宽高要手动获取
                Point size = getImageSize(data);
                width = size.x;
                height = size.y;
            }
    
            // 处理获取到的第一行数据
            handleMediaRowData(data, dateTaken, width, height);
    
        } catch (Exception e) {
            CrashReport.postCatchedException(e);
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }
    
    private Point getImageSize(String imagePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);
        return new Point(options.outWidth, options.outHeight);
    }
    
    /**
     * 处理获取到的一行数据
     */
    private void handleMediaRowData(String data, long dateTaken, int width, int height) {
        if (checkScreenShot(data, dateTaken, width, height)) {
            Log.d(TAG, "ScreenShot: path = " + data + "; size = " + width + " * " + height
                    + "; date = " + dateTaken);
            if (mListener != null && !checkCallback(data)) {
                mListener.onShot(data);
            }
        } else {
            // 如果在观察区间媒体数据库有数据改变,又不符合截屏规则,则输出到 log 待分析
            Log.w(TAG, "Media content changed, but not screenshot: path = " + data
                    + "; size = " + width + " * " + height + "; date = " + dateTaken);
        }
    }
    
    /**
     * 判断指定的数据行是否符合截屏条件
     */
    private boolean checkScreenShot(String data, long dateTaken, int width, int height) {
        /*
         * 判断依据一: 时间判断
         */
        // 如果加入数据库的时间在开始监听之前, 或者与当前时间相差大于10秒, 则认为当前没有截屏
        if (dateTaken < mStartListenTime || (System.currentTimeMillis() - dateTaken) > 10 * 1000) {
            return false;
        }
    
        /*
         * 判断依据二: 尺寸判断
         */
        if (sScreenRealSize != null) {
            // 如果图片尺寸超出屏幕, 则认为当前没有截屏
            if (!((width <= sScreenRealSize.x && height <= sScreenRealSize.y)
                    || (height <= sScreenRealSize.x && width <= sScreenRealSize.y))) {
                return false;
            }
        }
    
        /*
         * 判断依据三: 路径判断
         */
        if (TextUtils.isEmpty(data)) {
            return false;
        }
        data = data.toLowerCase();
        // 判断图片路径是否含有指定的关键字之一, 如果有, 则认为当前截屏了
        for (String keyWork : KEYWORDS) {
            if (data.contains(keyWork)) {
                return true;
            }
        }
    
        return false;
    }
    
    /**
     * 判断是否已回调过, 某些手机ROM截屏一次会发出多次内容改变的通知; <br/>
     * 删除一个图片也会发通知, 同时防止删除图片时误将上一张符合截屏规则的图片当做是当前截屏.
     */
    private boolean checkCallback(String imagePath) {
        if (sHasCallbackPaths.contains(imagePath)) {
            Log.d(TAG, "ScreenShot: imgPath has done"
                    + "; imagePath = " + imagePath);
            return true;
        }
        // 大概缓存15~20条记录便可
        if (sHasCallbackPaths.size() >= 20) {
            for (int i = 0; i < 5; i++) {
                sHasCallbackPaths.remove(0);
            }
        }
        sHasCallbackPaths.add(imagePath);
        return false;
    }
    
    /**
     * 获取屏幕分辨率
     */
    private Point getRealScreenSize() {
        Point screenSize = null;
        try {
            screenSize = new Point();
            WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
            Display defaultDisplay = windowManager.getDefaultDisplay();
            defaultDisplay.getRealSize(screenSize);
        } catch (Exception e) {
            CrashReport.postCatchedException(e);
        }
        return screenSize;
    }
    
    
    /**
     * 设置截屏监听器
     */
    public void setListener(OnScreenShotListener listener) {
        mListener = listener;
    }
    
    public interface OnScreenShotListener {
        void onShot(String imagePath);
    }
    
    private static void assertInMainThread() {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            StackTraceElement[] elements = Thread.currentThread().getStackTrace();
            String methodMsg = null;
            if (elements != null && elements.length >= 4) {
                methodMsg = elements[3].toString();
            }
            throw new IllegalStateException("Call the method must be in main thread: " + methodMsg);
        }
    }
    
    /**
     * 媒体内容观察者(观察媒体数据库的改变)
     */
    private class MediaContentObserver extends ContentObserver {
    
        private Uri mContentUri;
    
        public MediaContentObserver(Uri contentUri, Handler handler) {
            super(handler);
            mContentUri = contentUri;
        }
    
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            try {
                if (null != mContext && null != mRxPermissions && ActivityUtils.getTopActivityName(mContext).contains("OrderDetailsActivity")) {
                    if (!isExcuteRequest && null != mContentUri) {
                        isExcuteRequest = true;
                        checkReadPermission((AppCompatActivity) mContext, mContentUri);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * @param excuteRequest true 不允许回调
     */
    public synchronized void changeStatus(boolean excuteRequest) {
        if (isExcuteRequest != excuteRequest)
            isExcuteRequest = excuteRequest;
    }
    
    /**
     * 检查
     */
    private void checkReadPermission(AppCompatActivity appCompatActivity, Uri mContentUri) {
        OrderDetailPermissionUtils.Companion.getInstence().showPermissionsTwoDialog(appCompatActivity, "照片权限,用于存储照片", new SyPermissionOtherUtils.PermissionCallBack() {
            @Override
            public void open() {
                Disposable subscribe = mRxPermissions.requestEach(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Permission>() {
                            @Override
                            public void accept(Permission permission) throws Exception {
                                if (permission.granted) {
                                    handleMediaContentChange(mContentUri);
                                    //用户拒绝了该权限,//1
                                } else if (permission.shouldShowRequestPermissionRationale) {
                                    //dakai setting
                                    // 用户拒绝了该权限,』
                                    isExcuteRequest = false;
                                } else {//2
                                    isExcuteRequest = false;
                                    //不再提醒
                                    SyPermissionOtherUtils.setPermissionsRefuse(Manifest.permission.READ_EXTERNAL_STORAGE);
                                }
                            }
                        });
            }
    
            @Override
            public void cancel() {
                isExcuteRequest = false;
            }
    
            @Override
            public void openSetting() {
                OrderDetailPermissionUtils.Companion.getInstence().jumpPhoneSetting(appCompatActivity, 8888);
            }
        }, Manifest.permission.READ_EXTERNAL_STORAGE);
    }
    

    }

    相关文章

      网友评论

        本文标题:Android 获取系统截屏回调处理逻辑

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