系统级应用设置系统时间和时区
1.直接根据时间戳设置系统时间,此方法简单,但是只能去设置时间:
SystemClock.setCurrentTimeMillis(long time)
2.此方法需要注意,系统应用还需要具备Root权限,能够直接在应用内写SU命令:
//curr_time 格式:MMddHHmmyyyy.ss 例:020110302018.35
public static void setSystemTime(Context context, String curr_time) {
try{
AlarmManager mAlarmManager = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
//此处就是设置时区
mAlarmManager.setTimeZone("Asia/Shanghai"); // Asia/Shanghai//GMT+08:00
}catch (Exception e){
e.printStackTrace();
}
try {
LogUtils.i("系统设置 开始同步服务器时间");
execSuCmd22("date " + curr_time
+ "\n busybox hwclock -w\n");
} catch (Exception e) {
LogUtils.i("系统设置 同步服务器时间失败");
e.printStackTrace();
}
}
/**
* 执行Android命令
*
* @param cmd 命令
*/
public static void execSuCmd22(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) {
Log.i("88888888", "88888888 同步服务器时间失败");
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
if (process != null) {
process.destroy();
}
} catch (Exception e) {
}
}
LogUtils.i("同步服务器时间成功");
}
本篇完,仅一个功能点共享。