安卓系統下 用C語言設定系統時間
阿新 • • 發佈:2019-01-22
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifndef _WIN32 //linux specific #include <unistd.h> #include <termios.h> #endif // !_WIN32 #ifndef _WIN32 #include <sys/ioctl.h> #include <linux/ioctl.h> #include <linux/rtc.h> #include <linux/android_alarm.h> #else #include <io.h> #endif int HelloWorld::set_system_time(int year, int month, int day, int hour, int mini, int sec) { #ifndef _WIN32 struct tm tm; struct tm _tm; struct timeval tv; time_t timep; _tm.tm_sec = sec; _tm.tm_min = mini; _tm.tm_hour = hour+1; _tm.tm_mday = day; _tm.tm_mon = month - 1; _tm.tm_year = year - 1900; timep = mktime(&_tm); tv.tv_sec = (long)timep; tv.tv_usec = 0; // if (settimeofday(&tv, NULL) < 0) { // return -1; // } // else { // return 0; // } int fd = open("/dev/alarm", O_RDWR); if (fd < 0) { return -1; } struct timespec ts; ts.tv_sec = tv.tv_sec; ts.tv_nsec = tv.tv_usec * 1000; int res = ioctl(fd, ANDROID_ALARM_SET_RTC, &ts); if (res < 0) { return -1; } close(fd); return 0; #endif return 0; }
settimeofday確定是不可以的。無論系統root過,還是xml加什麼permision都不可以。java的用這個SystemClock.setCurrentTimeMillis(when);就可以。搞了半天歪門邪道,想讓程式執行在system許可權下什麼的。。但是最終沒執行起來。關鍵字:android:sharedUserId="android.uid.system" . 修改Android.mk檔案,加入LOCAL_CERTIFICATE := platform這一行...總之很坑爹。。反正不行。如果有人用settimeofday可以。請告訴我,非常感謝。
後來google。。。。最近google不好上,天朝簡直坑爹。找到這個地方:https://android.googlesource.com/platform/frameworks/native/+/jb-mr0-release/libs/utils/SystemClock.cpp
一看,這才沒有絕望。我差點就想用c++呼叫java這種歪門邪路了。。。
對了,設定的時間,hour老是對不上,手動+1,不解釋,不造為啥。。。
僅此,備註。問題解決。