you cannot detect if an app is launched at a particular time ,but what you can certainly find out if any other app is in foreground.
public static boolean isForeground(Context ctx, String myPackage){
ActivityManager manager = (ActivityManager)
ctx.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > runningTaskInfo =
manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equals(myPackage)) {
return true;
}
return false;
}
To detect apps if they are just in the RAM , either in foreground or background, use this :
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo =
am.getRunningAppProcesses();
for (int i = 0; i < runningAppProcessInfo.size(); i++) {
if(runningAppProcessInfo.get(i).processName.equals("com.the.app.you.are.looking.for")
{
// Do you stuff
}
}
You can probabaly consider inititating BG check and trynna find out, if no. apps in foreground has increased by on which will means that a new app was launched.
Option 2:
I think we can use logcat and analyze it's output.
In all similar programs I have found this permission :
android.permission.READ_LOGS
It means all of them use it but it seems the program starts and after that our program (app protector) will start and bring front.
Use below code :
try
{
Process mLogcatProc = null;
BufferedReader reader = null;
mLogcatProc = Runtime.getRuntime().exec(new String[]{"logcat", "-d"});
reader = new BufferedReader(new
InputStreamReader(mLogcatProc.getInputStream()));
String line;
final StringBuilder log = new StringBuilder();
String separator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null)
{
log.append(line);
log.append(separator);
}
String w = log.toString();
Toast.makeText(getApplicationContext(),w, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
Notes :-Third part applications cant use the systen permission to read log for security reasons aboove Android 4.1
Read more here,
https://commonsware.com/blog/2012/07/12/read-logs-regression.html.Option 1 is your best bet.