Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically get the network operator's time (android)

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 telephonyManager =((TelephonyManager)Context.getSystemService(Context.TELEPHONY_SERVICE));
String operatorName = telephonyManager.getNetworkOperatorName();

This is to get the operator's name programmatically. But how to get the operator's current time? If the user has changed the time manually, then the app will change it to operator's current time.

I did a google search too :

Unable to find a better one. If its already asked on stackoverflow, excuse and please provide the link.

EDIT:

I forgot to mention that it is an offline app where i am not getting the internet permission from the user.

Thanks.

like image 420
Nagaraj Alagusundaram Avatar asked Aug 19 '13 11:08

Nagaraj Alagusundaram


1 Answers

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.

like image 154
Aleks G Avatar answered Oct 30 '22 05:10

Aleks G