0

I am currently working on AppLocker App which detects app opening by the user using UsageStatsManager. I use background service BackgroundServices.java for detection. But when we open notification bar by scrolling down, UsageStatsManager randomly takes any notification as running and opens LockScreen unnecessarily.

Main block for detecting and returning current-using-app BackgroundServices.java

 private String printForegroundTask() {
        String currentApp = "NULL";
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
            long time = System.currentTimeMillis();
            List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  time - 1000*1000, time);
            if (appList != null && appList.size() > 0) {
                SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
                for (UsageStats usageStats : appList) {
                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                }
                if (mySortedMap != null && !mySortedMap.isEmpty()) {
                    currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                }
            }
        } else {
            ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
            currentApp = tasks.get(0).processName;
        }
        // Log.e("AppLockerService", "Current App in foreground is: " + currentApp)
            return currentApp;
    }
Hritik Bhat
  • 106
  • 5

1 Answers1

0

So I am posting this to share the answer to the above problem. I was searching a lot throughout the Internet and found this.

Solution

I would like to thank Muthukrishnan Rajendran for answering the question. His Profile Link

I hope that people who are searching answer related to the problem will get ease to solve it through the link. Thank You

Hritik Bhat
  • 106
  • 5