繁体   English   中英

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

[英]How to detect current foreground app when foreground service is running

我目前正在使用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,这是我正在使用的程序包名称。

您无法获得自Android L以来的顶级活动,但是有一种使用ActivityManager.RunningAppProcessInfo的变通办法,它很重要 ,它可以让用户启动应用程序,请查看以下先前的答案

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM