最近碰到修改系統時間的需求,折騰了一段時間,發現網上有一種方法是通過
命令的方式修改的。
在這裏感謝那位老兄的方法。
TimeManager.setSystemTime:
public static void setSystemTime(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd.HHmmss", Locale.getDefault());
String dateTime = format.format(date);
ArrayList<String> list = new ArrayList<>();
Map<String, String> map = System.getenv();//獲取環境變量的值
for (String env : map.keySet()) {
list.add(env + "=" + map.get(env));
}
String[] str = list.toArray(new String[0]);
String commend = "date -s\"" + dateTime + "\"";
try {
Runtime.getRuntime().exec(new String[]{"su", "-c", commend}, str);
} catch (IOException e) {
e.printStackTrace();
}
}
首先將Date格式的時間轉化成需要的yyyyMMdd.HHmmss格式。第二個參數
Locale.getDefault()獲取缺省本地國家代碼設置,然後根據這個代碼顯示成不
同的格式。
假設現有一個TextView上顯示時間爲2016/10/13/18/04 ,現在要將
這個字符串轉換成Date類型作爲參數。
Date date = new Date();
date.setYear(Integer.valueOf(dateTxt.getText().toString().substring(0, 4)) - 1900);
date.setMonth(Integer.valueOf(dateTxt.getText().toString().substring(5, 7)) - 1);
date.setDate(Integer.valueOf(dateTxt.getText().toString().substring(8, 10)));
date.setHours(Integer.valueOf(timeTxt.getText().toString().substring(11, 13)));
date.setMinutes(Integer.valueOf(timeTxt.getText().toString().substring(14, 16)));
TimeManager.setSystemTime(date);
年份和實際年份會相差1900,而月份相差1,因此需要減去。然後將
Date作爲參數傳進去就可以修改系統時間了。