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) {
}
}
}
參考:
https://www.cnblogs.com/tc310/p/10922464.html