1. 程式人生 > >android獲取系統時間精確到微秒

android獲取系統時間精確到微秒

最近專案開發,需要獲取到當前時間並且精確到微秒。但是一查資料發現似乎只能精確到到毫秒級,通過

SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");

        String str = formatter.format(new Date());

或者

Calendar calendar = Calendar.getInstance();
        long mm = calendar.get(Calendar.MILLISECOND);

最後幾經周折,可以通過c程式碼得到得到當前時間的微秒值,於是便通過jni方式得到了時間的微秒值。

其中c程式碼:

JNIEXPORT jlongArray JNICALL Java_com_test_ndkhelloword_MainActivity_getTimesFromJni(
        JNIEnv *env, jobject thiz) {
    jlongArray time = env->NewLongArray(2);
    jlong temp[] = { 0, 0 };
    struct timeval begin;
    gettimeofday(&begin, NULL);
    temp[0] = begin.tv_sec;
    temp[1] = begin.tv_usec;
    env->SetLongArrayRegion(time, 0, 2, temp);
    return time;
}

還好最後找到了辦法,特此分享。