Programmatically get the network operator's time (android)

后端 未结 1 1043
遇见更好的自我
遇见更好的自我 2021-01-11 15:22

I need to get the current time for my android app. The time should be operator\'s time and not the local time set by the user.

TelephonyManager telephonyMan         


        
1条回答
  •  有刺的猬
    2021-01-11 15:47

    The simple answer is that it cannot be done. In order to accomplish what you want, your app would need to do two things:

    1. send service message to the network operator; and
    2. change local time on the device.

    Both of these operations require system-level privileges. That is, your app needs to be signed with a system key (i.e. one issued by Google to device manufacturers) in order to access these functions.

    What you can do is get the current time from an NTP server. There are plenty free-to-use NTP servers on the internet. A sample code to get such time is this:

    String timeServer = "0.pool.ntp.org";
    
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(timeServer);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    long returnTime = timeInfo.getReturnTime();
    
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(returnTime);
    

    Now your cal object contains the real time from the NTP server and not the time from the device. Still, you will not be able to set the time as the device's current time.

    0 讨论(0)
提交回复
热议问题