get Foreground App - Android App

Android examples for App:App Running

Description

get Foreground App

Demo Code


//package com.java2s;
import android.annotation.TargetApi;

import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.os.Build;

import java.util.List;

public class Main {

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static String getForegroundApp(Context context) {
        UsageStatsManager usageStatsManager = (UsageStatsManager) context
                .getSystemService(Context.USAGE_STATS_SERVICE);
        long ts = System.currentTimeMillis();
        List<UsageStats> queryUsageStats = usageStatsManager
                .queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                        ts - 2000, ts);/*from  w  w  w.  j  a  v a  2  s  . co m*/
        if (queryUsageStats == null || queryUsageStats.isEmpty()) {
            return null;
        }
        UsageStats recentStats = null;
        for (UsageStats usageStats : queryUsageStats) {
            if (recentStats == null
                    || recentStats.getLastTimeUsed() < usageStats
                            .getLastTimeUsed()) {
                recentStats = usageStats;
            }
        }
        return recentStats.getPackageName();
    }
}

Related Tutorials