在android中监控应用程序

时间:2014-08-07 10:31:33

标签: android

美好的一天。我可以使用android sdk获取用户正在使用的Android应用程序的名称,以及此应用程序中的会话时间。即服务将收到应用程序的名称和会话,并将其发送到数据库。

解决。这是我的洗礼

 private String getRunningAppByActivity(){
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        // get the info from the currently running task
        List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);

        ComponentName componentInfo = taskInfo.get(0).topActivity;
        String name=componentInfo.getPackageName();

        final PackageManager pm = context.getPackageManager();
        ApplicationInfo ai;
        try {
            ai = pm.getApplicationInfo(name, 0);
        } catch (final PackageManager.NameNotFoundException e) {
            ai = null;
        }
        final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
        Log.d("APPLICATION_NAME", applicationName);
        return applicationName;
    }

1 个答案:

答案 0 :(得分:1)

试试这个:

     ActivityManager activityManager = (ActivityManager)            
     {context}.getSystemService(Context.ACTIVITY_SERVICE);
     List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    final PackageManager pm = getApplicationContext().getPackageManager();

    for (RunningTaskInfo task : tasks) {

    try {
        ai = pm.getApplicationInfo(task.baseActivity.getPackageName(), 0);
       } catch (final NameNotFoundException e) {
    ai = null;
     }
      String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai): "(unknown)");

    }