Android 获取顶层应用及存活

public static boolean isNewTopActivity(String name,Context context) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        UsageStatsManager usm = (UsageStatsManager) context.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()) {
                String currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                //Log.d("TouchOnlineReceiver","currentApp = " + currentApp);
                return currentApp.contains(name);
            }
        }
        return false;
    } else {
        //android 5.0 以上 获取自生(或者sharedUserId相同)顶层应用包名
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfos = am.getRunningTasks(1);
        ComponentName cn = null;
        if(taskInfos.size()>0){
            cn = taskInfos.get(0).topActivity;
        }else {
            return false;
        }
        Log.e("=====","classname = " + cn.getClassName());
        return cn.getClassName().contains(name);
    }

}
 /** 判断服务是否在运行
 with Android O(8.0) this is now deprecated and will only return information about the calling apps services
 * @param context
 * @param serviceName
 * @return
 */
public boolean isRunService(Context context,String serviceName) {
    ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        //Log.e(TAG,service.service.getClassName()+" service name");
        if (service.service.getClassName().contains(serviceName)) {
            return true;
        }
    }
    return false;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值