[英]How to detect current foreground app when foreground service is running
I'm currently working on an AppLock which includes service that detects current foreground app but the problem is the service keeps returning the AppLock itself as the current foreground app even after I minimize it or close the AppLock. 我目前正在使用AppLock,其中包括检测当前前景应用程序的服务,但是问题是,即使我将其最小化或关闭了AppLock,该服务仍会继续将AppLock本身作为当前前景应用程序返回。 Is there a way to fix this? 有没有办法解决这个问题?
I'm aware of other similar questions have been answered but I don't see anyone else having the same problem as me as far as I can see. 我知道已经回答了其他类似的问题,但据我所知,没有其他人遇到与我相同的问题。
Below is the code I'm using to detect the foreground app 下面是我用来检测前台应用程序的代码
public String getForegroundApp() {
String currentApp = "NULL";
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<Long, UsageStats>();
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.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
return currentApp;
}
public int onStartCommand(Intent intent, int flags, int startId) {
if(foreapp.equals(lockedApp)){
Intent intentp3=new Intent(getApplicationContext(), PasswordPage3.class);
intentp3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentp3);
}
return START_STICKY;
}
The receiver I'm using to start the service: 我用来启动服务的接收器:
public class RestartReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent lol) {
Log.i("running in the back","restarting");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, MyService.class));
} else {
context.startService(new Intent(context, MyService.class));
}
}
}
Note: foreapp and lockedApp are both String variables 注意:foreapp和lockedApp都是String变量
The String that currentApp returns are constantly com.example.apptest3 which is the package name that I'm working on. currentApp返回的字符串始终是com.example.apptest3,这是我正在使用的程序包名称。
您无法获得自Android L以来的顶级活动,但是有一种使用ActivityManager.RunningAppProcessInfo的变通办法,它很重要 ,它可以让用户启动应用程序,请查看以下先前的答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.