Android 監(jiān)聽系統(tǒng)截屏操作(已適配Android Q)

Android系統(tǒng)沒有提供現(xiàn)成的Api來監(jiān)聽到用戶的截屏操作毒返,所以我們需要自己實現(xiàn)對用戶截屏的監(jiān)聽。

針對這個特殊的需求舷手,比較可行的方案是利用系統(tǒng)的媒體數(shù)據(jù)庫拧簸。每當(dāng)我們產(chǎn)生一張新圖片,系統(tǒng)都會把這張圖片的詳細信息加入到媒體數(shù)據(jù)庫男窟,并發(fā)出內(nèi)容改變通知盆赤,我們可以利用內(nèi)容觀察者(ContentObserver)監(jiān)聽媒體數(shù)據(jù)庫的變化,當(dāng)數(shù)據(jù)庫有變化時歉眷,獲取最后插入的一條圖片數(shù)據(jù)牺六,如果該圖片符合特定的規(guī)則,則認為用戶截屏了汗捡。

于是我們需要監(jiān)聽兩個Uri:

  • 內(nèi)部存儲空間的 content:// 格式Uri:MediaStore.Images.Media.INTERNAL_CONTENT_URI
  • 主要外部存儲空間 content:// 格式Uri:MediaStore.Images.Media.EXTERNAL_CONTENT_URI

注:開始監(jiān)聽媒體數(shù)據(jù)庫變化之前淑际,不要忘了先獲取權(quán)限READ_EXTERNAL_STORAGE

定義一個內(nèi)容觀察者類:

/**
 * 媒體內(nèi)容觀察者(觀察媒體數(shù)據(jù)庫的改變)
 */
private class MediaContentObserver extends ContentObserver {

    private Uri mContentUri;

    public MediaContentObserver(Uri contentUri, Handler handler) {
        super(handler);
        mContentUri = contentUri;
    }

    @Override
    public void onChange(boolean selfChange) {
        LogUtils.e("ScreenShotListenManager  MediaContentObserver  onChange");
        super.onChange(selfChange);
        //通過媒體數(shù)據(jù)庫的內(nèi)容改變來判斷用戶是否執(zhí)行了截屏操作
    }
}

創(chuàng)建并注冊內(nèi)容觀察者

// 創(chuàng)建內(nèi)容觀察者
mInternalObserver = new MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mUiHandler);
mExternalObserver = new MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mUiHandler);

// 注冊內(nèi)容觀察者
mContext.getContentResolver().registerContentObserver(
        MediaStore.Images.Media.INTERNAL_CONTENT_URI,
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q,
        mInternalObserver
);
mContext.getContentResolver().registerContentObserver(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q,
        mExternalObserver
);

不需要監(jiān)聽內(nèi)容變化時,不要忘了注銷內(nèi)容觀察者

// 注銷內(nèi)容觀察者
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;
}

當(dāng)媒體內(nèi)容發(fā)生變化時扇住,會執(zhí)行ContentObserver 的onChange方法春缕。我們需要通過媒體數(shù)據(jù)庫的內(nèi)容改變來判斷用戶是否執(zhí)行了截屏操作:

獲取最近插入的一條數(shù)據(jù),判斷是否符合截屏圖片的特征艘蹋。如果符合锄贼,那么我們認為用戶進行了截圖操作。

public class ScreenShotListenManager {
    private static final String TAG = "ScreenShotListenManager";

    /**
     * 讀取媒體數(shù)據(jù)庫時需要讀取的列
     */
    private static final String[] MEDIA_PROJECTIONS = {
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
    };
    /**
     * 讀取媒體數(shù)據(jù)庫時需要讀取的列, 其中 WIDTH 和 HEIGHT 字段在 API 16 以后才有
     */
    private static final String[] MEDIA_PROJECTIONS_API_16 = {
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
            MediaStore.Images.ImageColumns.WIDTH,
            MediaStore.Images.ImageColumns.HEIGHT,
    };

    /**
     * 截屏依據(jù)中的路徑判斷關(guān)鍵字
     */
    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"
    };

    private static Point sScreenRealSize;

    /**
     * 已回調(diào)過的路徑
     */
    private final static List<String> sHasCallbackPaths = new ArrayList<String>();

    private Context mContext;

    private OnScreenShotListener mListener;

    private long mStartListenTime;

    /**
     * 內(nèi)部存儲器內(nèi)容觀察者
     */
    private MediaContentObserver mInternalObserver;

    /**
     * 外部存儲器內(nèi)容觀察者
     */
    private MediaContentObserver mExternalObserver;

    /**
     * 運行在 UI 線程的 Handler, 用于運行監(jiān)聽器回調(diào)
     */
    private final Handler mUiHandler = new Handler(Looper.getMainLooper());

    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.e(TAG, "Get screen real size failed.");
            }
        }
    }

    public static ScreenShotListenManager newInstance(Context context) {
        assertInMainThread();
        return new ScreenShotListenManager(context);
    }

    /**
     * 啟動監(jiān)聽
     */
    public void startListen() {
        assertInMainThread();

        // 記錄開始監(jiān)聽的時間戳
        mStartListenTime = System.currentTimeMillis();

        // 創(chuàng)建內(nèi)容觀察者
        mInternalObserver = new MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mUiHandler);
        mExternalObserver = new MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mUiHandler);

        // 注冊內(nèi)容觀察者
        mContext.getContentResolver().registerContentObserver(
                MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q,
                mInternalObserver
        );
        mContext.getContentResolver().registerContentObserver(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q,
                mExternalObserver
        );
        LogUtils.e("ScreenShotListenManager  startListen");
    }

    /**
     * 停止監(jiān)聽
     */
    public void stopListen() {
        assertInMainThread();

        // 注銷內(nèi)容觀察者
        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;
        }

        // 清空數(shù)據(jù)
        mStartListenTime = 0;
//        sHasCallbackPaths.clear();

        //切記2狙怠T廴ⅰ!:必須設(shè)置為空 可能mListener 會隱式持有Activity導(dǎo)致釋放不掉
        mListener = null;
    }

    /**
     * 處理媒體數(shù)據(jù)庫的內(nèi)容改變
     */
    private void handleMediaContentChange(Uri contentUri) {
        Cursor cursor = null;
        try {
            // 數(shù)據(jù)改變時查詢數(shù)據(jù)庫中最后加入的一條數(shù)據(jù)
            cursor = mContext.getContentResolver().query(
                    contentUri,
                    Build.VERSION.SDK_INT < 16 ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,
                    null,
                    null,
                    MediaStore.Images.ImageColumns.DATE_ADDED + " 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;
            if (Build.VERSION.SDK_INT >= 16) {
                widthIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.WIDTH);
                heightIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.HEIGHT);
            }

            // 獲取行數(shù)據(jù)
            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;
            }

            // 處理獲取到的第一行數(shù)據(jù)
            handleMediaRowData(data, dateTaken, width, height);

        } catch (Exception e) {
            e.printStackTrace();

        } 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);
    }

    /**
     * 處理獲取到的一行數(shù)據(jù)
     */
    private void handleMediaRowData(String data, long dateTaken, int width, int height) {
        if (CommunityApplication.self.isComeBack()) {
            return;
        }
        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 {
            // 如果在觀察區(qū)間媒體數(shù)據(jù)庫有數(shù)據(jù)改變强品,又不符合截屏規(guī)則,則輸出到 log 待分析
            Log.w(TAG, "Media content changed, but not screenshot: path = " + data
                    + "; size = " + width + " * " + height + "; date = " + dateTaken);
        }
    }

    /**
     * 判斷指定的數(shù)據(jù)行是否符合截屏條件
     */
    private boolean checkScreenShot(String data, long dateTaken, int width, int height) {
        /*
         * 判斷依據(jù)一: 時間判斷
         */
        // 如果加入數(shù)據(jù)庫的時間在開始監(jiān)聽之前, 或者與當(dāng)前時間相差大于10秒, 則認為當(dāng)前沒有截屏
        if (dateTaken < mStartListenTime || (System.currentTimeMillis() - dateTaken) > 10 * 1000) {
            return false;
        }

        /*
         * 判斷依據(jù)二: 尺寸判斷
         */
        if (sScreenRealSize != null) {
            // 如果圖片尺寸超出屏幕, 則認為當(dāng)前沒有截屏
            if (!((width <= sScreenRealSize.x && height <= sScreenRealSize.y)
                    || (height <= sScreenRealSize.x && width <= sScreenRealSize.y))) {
                return false;
            }
        }

        /*
         * 判斷依據(jù)三: 路徑判斷
         */
        if (TextUtils.isEmpty(data)) {
            return false;
        }
        data = data.toLowerCase();
        // 判斷圖片路徑是否含有指定的關(guān)鍵字之一, 如果有, 則認為當(dāng)前截屏了
        for (String keyWork : KEYWORDS) {
            if (data.contains(keyWork)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判斷是否已回調(diào)過, 某些手機ROM截屏一次會發(fā)出多次內(nèi)容改變的通知; <br/>
     * 刪除一個圖片也會發(fā)通知, 同時防止刪除圖片時誤將上一張符合截屏規(guī)則的圖片當(dāng)做是當(dāng)前截屏.
     */
    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);
            if (windowManager != null) {
                Display defaultDisplay = windowManager.getDefaultDisplay();
                defaultDisplay.getRealSize(screenSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return screenSize;
    }

    /**
     * 設(shè)置截屏監(jiān)聽器
     */
    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);
        }
    }

    /**
     * 媒體內(nèi)容觀察者(觀察媒體數(shù)據(jù)庫的改變)
     */
    private class MediaContentObserver extends ContentObserver {

        private Uri mContentUri;

        public MediaContentObserver(Uri contentUri, Handler handler) {
            super(handler);
            mContentUri = contentUri;
        }

        @Override
        public void onChange(boolean selfChange) {
            LogUtils.e("ScreenShotListenManager  MediaContentObserver  onChange");
            super.onChange(selfChange);
            handleMediaContentChange(mContentUri);
        }
    }
}

關(guān)于網(wǎng)上盛傳的Android Q版本無法檢測到媒體數(shù)據(jù)庫變化的問題屈糊,我也是采取Android Q(10) ContentObserver 不回調(diào) onChange這篇文章提供的解決方法:在Android Q版本上調(diào)用注冊媒體數(shù)據(jù)庫監(jiān)聽的方法registerContentObserver時傳入 notifyForDescendants參數(shù)值改為 true的榛,Android Q之前的版本仍然傳入 false。

于是查看了一下文檔上關(guān)于參數(shù)notifyForDescendants的介紹逻锐,大致內(nèi)容如下:

* @param notifyForDescendants When false, the observer will be notified
 *            whenever a change occurs to the exact URI specified by
 *            <code>uri</code> or to one of the URI's ancestors in the path
 *            hierarchy. When true, the observer will also be notified
 *            whenever a change occurs to the URI's descendants in the path
 *            hierarchy.

如果值為false夫晌,則只要指定的URI或路徑層次結(jié)構(gòu)中URI的祖先之一發(fā)生變化雕薪,就會通知觀察者。 如果為true晓淀,則每當(dāng)路徑層次結(jié)構(gòu)中URI的后代發(fā)生更改時所袁,也會通知觀察者。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末凶掰,一起剝皮案震驚了整個濱河市燥爷,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌懦窘,老刑警劉巖前翎,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異畅涂,居然都是意外死亡港华,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門午衰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來立宜,“玉大人,你說我怎么就攤上這事臊岸〕仁” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵扇单,是天一觀的道長商模。 經(jīng)常有香客問我,道長蜘澜,這世上最難降的妖魔是什么施流? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮鄙信,結(jié)果婚禮上瞪醋,老公的妹妹穿的比我還像新娘。我一直安慰自己装诡,他們只是感情好银受,可當(dāng)我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著鸦采,像睡著了一般宾巍。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上渔伯,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天顶霞,我揣著相機與錄音,去河邊找鬼锣吼。 笑死选浑,一個胖子當(dāng)著我的面吹牛蓝厌,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播古徒,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼拓提,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了隧膘?” 一聲冷哼從身側(cè)響起代态,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎舀寓,沒想到半個月后胆数,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡互墓,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年必尼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片篡撵。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡判莉,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出育谬,到底是詐尸還是另有隱情券盅,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布膛檀,位于F島的核電站锰镀,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏咖刃。R本人自食惡果不足惜泳炉,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望嚎杨。 院中可真熱鬧花鹅,春花似錦、人聲如沸枫浙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽箩帚。三九已至真友,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間紧帕,已是汗流浹背锻狗。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留焕参,地道東北人轻纪。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像叠纷,于是被迫代替她去往敵國和親刻帚。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,864評論 2 354