检测哪个应用已在android中启动 [英] Detect which app has been launched in android

查看:111
本文介绍了检测哪个应用已在android中启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测用户已在我的应用程序中启动了哪个应用程序,即即使我的应用程序未在前台或后台运行,当用户启动Whatsapp时也应通知我的应用程序。

How to detect which app has been launched by user in my app i.e my application should get notified when Whatsapp is launched by user even if my app is not running in foreground or background.

远足信使与辅助功能已实现相同的功能。

hike messenger has achieved same functionality with accessibility service.

如何解决此问题?

提前谢谢!!

推荐答案

根据运行应用程序的Android版本,您将不得不使用不同的方法。
在Pre-Lollipop设备上,非常简单:

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

如果您使用的是Lollipop或更新的设备,则必须使用UsageStatsManager类,这需要您的应用程序被授予特定权限

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

最后,这将为用户启动Android权限授予活动:

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

希望有帮助

这篇关于检测哪个应用已在android中启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆