I'm working on lock application , In which when user open any app . my app will trigger and if it match with my blocklist then i'm showing lock screen to user.
What I have done so far.
public static String getTopAppName(Context context) {
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String strName = "";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
strName = getLollipopFGAppPackageName(context);
} else {
strName = mActivityManager.getRunningTasks(1).get(0).topActivity.getClassName();
}}
}
private static String getLollipopFGAppPackageName(Context ctx) {
try {
UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
long milliSecs = 60 * 1000;
Date date = new Date();
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
if (queryUsageStats.size() > 0) {
Log.i("LPU", "queryUsageStats size: " + queryUsageStats.size());
}
long recentTime = 0;
String recentPkg = "";
for (int i = 0; i < queryUsageStats.size(); i++) {
UsageStats stats = queryUsageStats.get(i);
if (i == 0 && !"org.pervacio.pvadiag".equals(stats.getPackageName())) {
Log.i("LPU", "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
}
if (stats.getLastTimeStamp() > recentTime) {
recentTime = stats.getLastTimeStamp();
recentPkg = stats.getPackageName();
}
}
return recentPkg;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
I'm following this SO Answer to get top running activity in device above Lollipop. I have created background service for that.
Problem I'm facing :
1. When user block any apps from my application , I'm getting package name of that app . for example (com.google.android.talk, com.google.android.apps.maps, com.android.chrome).
At the time of service running in background . I'm getting top package name com.google.android.gsf
for all google apps (maps , hangout ). So it's difficult for me to identify particular app .
I think the problem is in getLollipopFGAppPackageName()
but I can't figure out what.
2. As mentioned in Some SO posts that getLollipopFGAppPackageName()
can only be used at debug time not for actual implementation . So if I wont use this then what might be the correct way to implement this kind of functionality (lock app) in devices above lollipop.
Any help or guidance would be great .Thanks