我应该如何计算android中应用程序的启动次数

时间:2013-09-12 06:17:27

标签: android

我可以使用以下代码选择所有已安装的应用程序:

ActivityManager am = (ActivityManager)context.getSystemService(Activity.ACTIVITY_SERVICE);
    List Runningtasks = am.getRunningAppProcesses();

但我想要每个应用程序的启动次数?

2 个答案:

答案 0 :(得分:3)

使用“SharedPreferences”获取计数非常简单。 将以下代码放在OnCreate方法下。

//声明必要的变量

  SharedPreferences sharedPreferences;
  int count;

  sharedPreferences = getPreferences(0);
  int count = sharedPreferences.getInt("numRun", 0);
  count++;
  sharedPreferences.edit().putInt("numRun", count).commit(); 

答案 1 :(得分:0)

您可以在前台使用轮询当前应用程序 通过询问当前正在运行的任务。

int currentUidInFront = 0;
    while(true)
    {
    ActivityManager actMan = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<RunningTaskInfo> runningApps = actMan.getRunningTasks(1024);
    RunningTaskInfo runningTask = runningApps.get(0);
    int uidInFront = getApplicationContext().getPackageManager().getApplicationInfo(runningTask.topActivity.getPackageName(),1).uid;

    //chack if the current application is changed
    if(currentUidInFront != uidInFront)
    {
       currentUidInFront = uidInFront;
       Log.i("Changed running application",runningTask.topActivity.flattenToShortString());
    }  
  sleep(1000);
}

希望这有帮助。享受