您的位置:首页 > 编程语言 > C语言/C++

安卓系统下 用C语言设置系统时间

2016-07-19 17:33 459 查看
#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,不解释,不造为啥。。。

仅此,备注。问题解决。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android java cocos2d-x