I tried to develop such an app, in the sense I want to lock all the applications in my device with a password whatever I want. But I didn\'t find any piece of code for the s
Looks like this is still a mystery as suggested by above mentioned comments.So I'm putting the code that helped me to solve this problem.
getForegroundApp
public String getForegroundApp() {
String currentApp = "NULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) this.mContext.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap 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.mContext.getSystemService(Context.ACTIVITY_SERVICE);
List tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
return currentApp;
}
Call getForegroundApp() and it will return a string which contains the name of the currentForegroundApp including the package name e.g. com.example.app
Now, to use this code, we need this line of code in Manifest file
and take user to Usage Data access Settings:
usageAccessSettingsPage
public void usageAccessSettingsPage(){
Intent intent = new Intent();
intent.setAction(Settings.ACTION_USAGE_ACCESS_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", mContext.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
or manually by finding in LockScreen and Security> Other security settings> Usage access data.
Now comes the part for blocking the app, this part is covered in Amit's answer very well. However, if someone is looking for a way to restrict user from using an app then a trick is to open home screen when a particular app is launched.
This could be done by calling the following method when the currentApp is equal to a blocked app
if(.equals currentApp){
showHomeScreen();
}
ShowHomeScreen
public boolean showHomeScreen(){
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(startMain);
return true;
}