# 设置设备的时间

新建个方法

 /**
     * 执行Android命令,设置系统时间
     * @param cmd  命令
     */
    public 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();
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

设置时间

 /**设置系统时间
         * @param timer  "092110202025.52";   // 传入时间格式 月日时分年.秒
         */
public void InitSetTime(String timer){
       AlarmManager mAlarmManager = (AlarmManager) 
	   wcontexts.getSystemService(Context.ALARM_SERVICE);
       mAlarmManager.setTimeZone("Asia/Shanghai"); // Asia/Shanghai//GMT+08:00
       execSuCmd("date " + timer);
}
1
2
3
4
5
6
7
8
9

js转换 timer

/*dateTime = 2021-8-19 16:16 格式*/
getTimer(dateTime) {
		if (!dateTime) return null
		let timeStr = null
		let timer = dateTime.split(' '),
			date = timer[0].split('-'),
			time = timer[1].split(':');
		if (date && time) {
			timeStr = date[1] + "" + date[2] + time[0] + time[1] + date[0] + "." + time[2]
		}
		return timeStr
	}
1
2
3
4
5
6
7
8
9
10
11
12