1、放一个按钮,直接调用系统的修改时间
Intent intent = new Intent(Settings.ACTION_DATE_SETTINGS);
startActivity(intent);
2、写个线程,每秒获取当前时间,发现时间更改就写入rtc
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Date date = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
Log.i(TAG, "时间time为: " + df.format(date));
tv_time_current.setText(df.format(date));
//execSuCmd("busybox hwclock -w\n");
Log.i(TAG, "时间: " + savetime);
long diff = Math.abs(savetime - date.getTime()) / 1000;
Log.i(TAG, "时间: " + savetime + "差值:" + diff);
savetime = date.getTime();
if (diff > 1) {
Log.i(TAG, "满足条件,写入RTC");
execSuCmd("busybox hwclock -w\n");
}
}
});
SystemClock.sleep(1000);
}
}
}).start();
3、su权限的函数:(系统需要有su权限)
/**
* 执行Android命令
*
* @param cmd 命令
*/
private static void execSuCmd(String cmd) {
Process process = null;
DataOutputStream os = null;
DataInputStream is = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + "\n");
os.writeBytes("exit\n");
os.flush();
int aa = process.waitFor();
is = new DataInputStream(process.getInputStream());
byte[] buffer = new byte[is.available()];
is.read(buffer);
String out = new String(buffer);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
if (process != null) {
process.destroy();
}
} catch (Exception e) {
}
}
}
参考: