How to find out the running/start time of android

2020-02-05 11:26发布

Is there anyway to find out the start time of an application?ActivityManager provides pids etc for each application process but doesn't tell for how long process is running.

2条回答
家丑人穷心不美
2楼-- · 2020-02-05 11:41

This will return process start time (since system boot):

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);
    }
}

To get process running time:

final long dt = SystemClock.elapsedRealtime() - getStartTime(Process.myPid());
查看更多
等我变得足够好
3楼-- · 2020-02-05 11:47

I don't know wether there's an API for this. But one approach would be to use something like:

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

To get the start time of your application and the just subtract that with the currenttime.

Might not be the best way, but that's what came to mind. (And I haven't tried it..)

Gl !

查看更多
登录 后发表回答