How to Detect When the User Launches Another App? (Android)

Android, Detect when other apps are launched

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();
}

And do not forget to add it's permission in Manifest file.

Detect When other Application opened or Launched

You cannot detect an App launch in Android. But you can get the list of currently open apps using this code and check if the app you're looking for is open or not:

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 also check if the app is running in the foreground using this method

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;
}

Detect which app has been launched in android

Depending on the Android version running your application, you will have to use different methods.
On Pre-Lollipop devices, it is pretty straight-forward:

String[] result = new String[2];

List<ActivityManager.RunningTaskInfo> runningTasks;
ComponentName componentInfo;

runningTasks = activityManager.getRunningTasks(1);
componentInfo = runningTasks.get(0).topActivity;
result[0] = componentInfo.getPackageName();
result[1] = componentInfo.getClassName();

If you are on a Lollipop or newer device, you have to use UsageStatsManager class, which requires your application to be granted specific permissions

//no inspection ResourceType
UsageStatsManager mUsageStatsManager = (UsageStatsManager)context.getSystemService("usagestats");
long time = System.currentTimeMillis();

// We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time);

// Sort the stats by the last time used
if(stats != null) {
SortedMap<Long,UsageStats> mySortedMap = new TreeMap<>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
}
if(mySortedMap != null && !mySortedMap.isEmpty()) {
return mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}

return null;

This will tell you if your apps has been granted permissions:

try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return (mode != AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}

And finally this will launch the Android permission granting activity for the user:

Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
activity.startActivity(intent);

Hope that helps

Android App Detect Other Activity

You will want to look at NotificationListenerService, this will let you receive calls from the system when new notifications are posted or removed, or their ranking changed.

Once you receive a callback from the NotificationListenerService, you will want to create a Toast.

Take a look at this tutorial should help you get started.

Best way to detect (any) app (i.e. activity) launch from a my background service

Perhaps my answer in this question might help you. Android how to know an app has been started and range apps priority according the starting times

Place that code inside your background service.

Based on the package name of the activity in the foreground, you can detect that app name by checking all the apps on the phone and matching it with the app that has the same package name.

Edit

Since you want a continuous check, you could use an AsyncTask(), and in the doInBackground() function, just keep getting the list of running activities in each iteration, like I have suggested in that link, and the first item in the taskInfo list will have the activity/app in the foreground. You can also provide another button in your app which on click you stop this , by keeping a bool variable in shared preferences (which you poll for in the while condition in doInBackGround() function of the AsyncTask()).

I have done something similar in the past, and it worked for me.



Related Topics



Leave a reply



Submit