【发布时间】:2010-09-09 13:56:03
【问题描述】:
有没有办法找出应用程序的启动时间?ActivityManager 为每个应用程序进程提供 pid 等,但没有说明进程运行了多长时间。
【问题讨论】:
-
您找到解决此问题的好方法了吗?我发现如果您还想要包名称、正在运行的活动名称等,获取 PID 也可能很麻烦。
-
@Bhups,你有什么想法吗,我们该怎么做?
有没有办法找出应用程序的启动时间?ActivityManager 为每个应用程序进程提供 pid 等,但没有说明进程运行了多长时间。
【问题讨论】:
这将返回进程开始时间(自系统启动以来):
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());
【讨论】:
我不知道是否有用于此的 API。但一种方法是使用类似的东西:
String pid = "yourpid";
BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( "ls -ld /proc/"+pid)) , 1000 );
获取应用程序的开始时间,然后将其与当前时间相减。
可能不是最好的方法,但这就是我想到的。 (而且我还没有尝试过..)
Gl!
【讨论】: