I'm currently working on an AppLock which includes service that detects current foreground app but the problem is the service keeps returning the AppLock itself as the current foreground app even after I minimize it or close the AppLock. Is there a way to fix this?
I'm aware of other similar questions have been answered but I don't see anyone else having the same problem as me as far as I can see.
Below is the code I'm using to detect the foreground app
public String getForegroundApp() {
String currentApp = "NULL";
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;
}
return currentApp;
}
public int onStartCommand(Intent intent, int flags, int startId) {
if(foreapp.equals(lockedApp)){
Intent intentp3=new Intent(getApplicationContext(), PasswordPage3.class);
intentp3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentp3);
}
return START_STICKY;
}
The receiver I'm using to start the service:
public class RestartReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent lol) {
Log.i("running in the back","restarting");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, MyService.class));
} else {
context.startService(new Intent(context, MyService.class));
}
}
}
Note: foreapp and lockedApp are both String variables
The String that currentApp returns are constantly com.example.apptest3 which is the package name that I'm working on.