【问题标题】:How to find out the running/start time of android application?如何找出android应用程序的运行/启动时间?
【发布时间】:2010-09-09 13:56:03
【问题描述】:

有没有办法找出应用程序的启动时间?ActivityManager 为每个应用程序进程提供 pid 等,但没有说明进程运行了多长时间。

【问题讨论】:

  • 您找到解决此问题的好方法了吗?我发现如果您还想要包名称、正在运行的活动名称等,获取 PID 也可能很麻烦。
  • @Bhups,你有什么想法吗,我们该怎么做?

标签: android process


【解决方案1】:

这将返回进程开始时间(自系统启动以来):

private static long getStartTime(final int pid) throws IOException {
    final String path = "/proc/" + pid + "/stat";
    final BufferedReader reader = new BufferedReader(new FileReader(path));
    final String stat;
    try {
        stat = reader.readLine();
    } finally {
        reader.close();
    }
    final String field2End = ") ";
    final String fieldSep = " ";
    final int fieldStartTime = 20;
    final int msInSec = 1000;
    try {
        final String[] fields = stat.substring(stat.lastIndexOf(field2End)).split(fieldSep);
        final long t = Long.parseLong(fields[fieldStartTime]);
        final int tckName = Class.forName("libcore.io.OsConstants").getField("_SC_CLK_TCK").getInt(null);
        final Object os = Class.forName("libcore.io.Libcore").getField("os").get(null);
        final long tck = (Long)os.getClass().getMethod("sysconf", Integer.TYPE).invoke(os, tckName);
        return t * msInSec / tck;
    } catch (final NumberFormatException e) {
        throw new IOException(e);
    } catch (final IndexOutOfBoundsException e) {
        throw new IOException(e);
    } catch (ReflectiveOperationException e) {
        throw new IOException(e);
    }
}

获取进程运行时间:

final long dt = SystemClock.elapsedRealtime() - getStartTime(Process.myPid());

【讨论】:

  • 这需要root权限吗?
  • 当时没有。
【解决方案2】:

我不知道是否有用于此的 API。但一种方法是使用类似的东西:

String pid = "yourpid";    
BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( "ls -ld /proc/"+pid)) , 1000 );

获取应用程序的开始时间,然后将其与当前时间相减。

可能不是最好的方法,但这就是我想到的。 (而且我还没有尝试过..)

Gl!

【讨论】:

  • 命令执行抛出异常。你能看看吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2012-05-12
  • 2014-10-11
相关资源
最近更新 更多