I have list of apps in my app, When i click any of them i want to start a service and that service it checks whether that app is foreground or not, if yes then it shows in the LogCat
which app is been opened. So in this case i have used Service class only, and its not showing logcat
message.
This is the Service class
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String openedApp = intent.getStringExtra("openedApp");
if(printForegroundTask().equals(openedApp)){
Log.e("FOREGROUND", "Current App in foreground is: " + openedApp);
// startActivity(lockIntent);
}
return START_STICKY;
}
private String printForegroundTask() {
@SuppressLint("WrongConstant") UsageStatsManager usm = (UsageStatsManager) this.getSystemService("usagestats");
long time = System.currentTimeMillis();
assert usm != null;
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
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);
assert am != null;
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
return currentApp;
}
and this is the MainActivity
@Override
public void onClickMethod(int position) {
final String ApplicationPackageName = adapter.stringList.get(position);
Intent appIntent = new Intent(getApplicationContext(),MyService.class);
appIntent.putExtra("openedApp",ApplicationPackageName);
if(isLocked ==true){
startService(appIntent);
Toast.makeText(getApplicationContext(),ApplicationPackageName+ " LOCKED ", Toast.LENGTH_SHORT).show();
isLocked=false;
}else{
stopService(appIntent);
Toast.makeText(getApplicationContext(),ApplicationPackageName+ " UNLOCKED ", Toast.LENGTH_SHORT).show();
isLocked=true;
}
}
i defined Service class in the Manifest and i gave the permission.
I expect to see the logcat
message when the app is in the foreground. But its not showing any message.