由于監(jiān)控在最頂端的App需要持續(xù)進行俐末,所以首先需要單獨開一個后臺進程奄侠,運行一個單例Manager。
初始化Manager
private TopAppManager() {
// workHandler
workerThread = new HandlerThread(getClass().getName());
workerThread.start();
workerThreadHandler = new Handler(workerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
monitorInWorkThread();
}
};
isAccessibilityAvailable = HSAccessibilityManager.getInstance().isAvailable();
isUsageAccessGranted = HSUsageAccessMgr.getInstance().checkPermission(new HSUsageAccessMgr.PermissionListener() {
@Override
public void onPermissionChanged(boolean isGranted) {
isUsageAccessGranted = isGranted;
if (isUsageAccessGranted && !isAccessibilityAvailable) {
resumeMonitor();
}
}
});
HSAccessibilityManager.getInstance().registerEvent(new HSAccessibilityManager.AccEventListener() {
@Override
public void onAvailable() {
isAccessibilityAvailable = true;
L.l("isAccessibilityAvailable:" + isAccessibilityAvailable);
pauseMonitor();
}
@Override
public void onEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
if (TextUtils.isEmpty(event.getPackageName()) || TextUtils.isEmpty(event.getClassName())) {
return;
}
ComponentName componentName = new ComponentName(event.getPackageName().toString(), event.getClassName().toString());
if (TopAppUtil.tryGetActivityInfo(componentName) == null) {
return;
}
tryToNotifyTopApp(event.getPackageName().toString());
}
}
@Override
public void onUnavailable(@HSTopAppManager.FailCode int code, String failMsg) {
L.l("onUnavailable code:" + code + " msg:" + failMsg);
isAccessibilityAvailable = false;
resumeMonitor();
L.l("resumeMonitor");
}
});
//sendBroadcast HSTopAppManager.BROADCAST_TOP_APP_MONITOR_INITIATED
Intent intent = new Intent(HSTopAppManager.BROADCAST_TOP_APP_MONITOR_INITIATED);
intent.putExtra(HSTopAppManager.EXTRA_DATA_TOP_APP, getTopApp());
intent.setPackage(HSApplication.getContext().getPackageName());
HSApplication.getContext().sendBroadcast(intent);
}
創(chuàng)建一個唯一的HandlerThread對象;使用HandlerThread對象在創(chuàng)建一個Handler旅急,并且重寫handleMessage方法
如果已經(jīng)獲得Accessibility的權(quán)限坠非,那么實現(xiàn)監(jiān)聽很容易,這里需要提前判定是否已經(jīng)有了這個權(quán)限盟迟,這個方法的實現(xiàn)潦闲,以后再寫。
如果已經(jīng)獲得UsageAccess權(quán)限歉闰,對于實現(xiàn)監(jiān)聽也非常重要,這里也在提前判斷是否已經(jīng)獲得UsageAccess權(quán)限凹炸。關(guān)于這個權(quán)限的判斷昼弟,以后會寫。
然后動態(tài)注冊廣播变骡,去監(jiān)聽亮屏芭逝、滅屏和用戶操作等廣播
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case Intent.ACTION_SCREEN_ON:
case Intent.ACTION_USER_PRESENT:
resumeMonitor();
break;
case Intent.ACTION_SCREEN_OFF:
pauseMonitor();
break;
}
}
};
未完待續(xù)……