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ā)生更改時所袁,也會通知觀察者。