运行前台服务时如何检测当前的前台应用程序

时间:2019-06-30 17:39:21

标签: java android

我目前正在使用AppLock,其中包括检测当前前景应用程序的服务,但问题是,即使我将其最小化或关闭了AppLock,该服务仍会继续将AppLock本身作为当前前景应用程序返回。有办法解决这个问题吗?

我知道已经回答了其他类似的问题,但据我所知,没有其他人遇到与我相同的问题。

下面是我用来检测前台应用程序的代码

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

我用来启动服务的接收器:

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

注意:foreapp和lockedApp都是String变量

currentApp返回的字符串始终是com.example.apptest3,这是我正在使用的程序包名称。

2 个答案:

答案 0 :(得分:0)

您无法获得Android L以来的热门活动,但是有一种解决方法是使用 ActivityManager.RunningAppProcessInfo 重要性来获取用户启动应用程序的时间,checkout these previous answers

答案 1 :(得分:0)

问题不再存在。我使用塔伦·夏尔马(Tarun Sharma)在先前的问题之一中提供的答案解决了该问题,如果有人遇到与我相同的问题,请here

相关问题