I'm working an app called 'Prevent Uninstall', in this app user creates 4 digit pin and I'm going to save this pin in sharedpreferences. My requirement is when user clicks uninstall button of any application a popup or window should be displayed to confirm the pin which is already created in my application. So is it possible?, if possible please help me, i got stuck at this point.
hello guys finally i have found a solution below..
first get the current activity on foreground
public boolean isConcernedAppIsInForeground() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> task = manager.getRunningTasks(5);
if (Build.VERSION.SDK_INT <= 20) {
if (task.size() > 0) {
ComponentName componentInfo = task.get(0).topActivity;
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (componentInfo.getPackageName().equals("com.google.android.packageinstaller")) {
currentApp_for = pakageName.get(i);
return true;
}
}
}
} else {
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (retriveNewApp().equals("com.google.android.packageinstaller")) {
currentApp_for = pakageName.get(i);
Log.e("DSSDSDCSDC", currentApp_for + " LLLLLL::::");
return true;
}
}
}
return false;
}
To get the current activity on foreground above api level 21+ use this code
private String retriveNewApp() {
String currentApp_for_ = null;
if (Build.VERSION.SDK_INT >= 21) {
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<>();
for (UsageStats usageStats : applist) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp_for_ = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
Log.e(">>>>>>>>>><<<", "Current App in foreground is: " + currentApp_for_);
} else {
Log.e("CCC>>C>C>C>", "User not given the permission: " + currentApp_for_);
}
}
return currentApp_for_;
}
Important permission
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
now check the current activity is in foreground or not using service
if (isConcernedAppIsInForeground()) {
if (!currentApp.matches(previousApp)) {
// if matches do your activity here..
startActivity(newIntent(context,Draw_Lock.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
previousApp = currentApp;
}
}
}
Note: When user clicks on uninstall button of any app alert dialog popups which is known as 'com.google.android.packageinstaller' activity check weather this activity is in foreground or not using service class