一、获取权限,使我们的app变成特权app,可参考https://www.cnblogs.com/javabull/p/12115397.html
二、编写逻辑代码
1 import java.net.URL; 2 import java.net.URLConnection; 3 4 public class SynchronizeTimeThread implements Runnable { 5 6 @Override 7 public void run() { 8 while (true){ 9 visitURL("https://www.baidu.com/"); 10 try { 11 Thread.sleep(360000);//定时更新 12 } catch (InterruptedException e) { 13 e.printStackTrace(); 14 } 15 } 16 } 17 18 /** 19 * 网址访问 20 * 21 * @param url 网址 22 * @return urlDate 对象网址时间 23 * 24 */ 25 private void visitURL(String url) { 26 try { 27 URL url1 = new URL(url); 28 URLConnection conn = url1.openConnection(); //生成连接对象 29 conn.connect(); //连接对象网页 30 Long date = conn.getDate(); 31 if (date!=null){ 32 SystemClock.setCurrentTimeMillis(date); 33 } 34 } catch (Exception e) { 35 e.printStackTrace(); 36 37 } 38 } 39 }
在MainActivity的onCreate中开启线程来获取网页上的时间,但要注意的是,我们还需要设置时区。
1 //更新系统时间 2 private void toSynchronizeSystemTime(){ 3 AlarmManager mAlarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);//获取服务 4 mAlarmManager.setTimeZone("Asia/Shanghai");//上海 5 Thread thread = new Thread(new SynchronizeTimeThread()); 6 thread.setName("ToGetTime"); 7 thread.start(); 8 }