---
title: "查询应用使用次数"
author: "yzyspy"
date: "2012-11-13T22:43:35Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2012-10-31T21:02:52Z"
id: 1704016
url: "https://yzyspy.iteye.com/blog/1704016"
---

http://www.eoeandroid.com/forum.php?mod=viewthread&tid=207309

```
//比较两个应用程序的启动次数和运行时间
public final int compare(ApplicationInfo a, ApplicationInfo b) {
            ComponentName aName = a.intent.getComponent();
            ComponentName bName = b.intent.getComponent();
            int result = 0;
//get usagestats service
            IUsageStats mUsageStatsService = IUsageStats.Stub
                        .asInterface(ServiceManager.getService("usagestats"));
            try {
//get PkgUsageStats
                PkgUsageStats aStats = mUsageStatsService
                        .getPkgUsageStats(aName);
                PkgUsageStats bStats = mUsageStatsService
                        .getPkgUsageStats(bName);
                if(aStats!=null && bStats!=null) {
                    if ((aStats.launchCount > bStats.launchCount)
                        || ((aStats.launchCount == bStats.launchCount) && (aStats.usageTime > bStats.usageTime)))
                    result = -1;
                    else if ((aStats.launchCount < bStats.launchCount)
                        || ((aStats.launchCount == bStats.launchCount) && (aStats.usageTime < bStats.usageTime)))
                    result = 1;
                    else {
                    result = 0;
                    }
                }else if(aStats!=null && bStats ==null) {
                    result = -1;
                } else if(aStats==null && bStats !=null) {
                    result = 1;
                }
            } catch (RemoteException e) {
                Log.i("TAG", "get package usage stats fail");
            }

            return result;
        }
```

 

```
ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
        Map<String,Integer> apptimes = am.getAllPackageLaunchCounts();
        
        Set<Entry<String,Integer>>  entryset = apptimes.entrySet();
        
        Iterator<Entry<String,Integer>> iterators = entryset.iterator();
        
        while(iterators.hasNext()){
            Entry<String,Integer> item= iterators.next();
            
            Log.d("yzy","key = "+item.getKey() +"  values ="+item.getValue());
        }
        
```