以编程方式获取网络运营商的时间(android) [英] Programmatically get the network operator's time (android)

查看:630
本文介绍了以编程方式获取网络运营商的时间(android)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取当前的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.

我做了一个 google search

无法找到更好的一个。如果它已经在stackoverflow上询问,请提供链接。

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

编辑:

我忘了提及这是一个离线应用程序,我没有得到用户的互联网许可。

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

谢谢。
(对不好的英语抱歉)

Thanks. (sorry for bad English)

推荐答案

简单的答案是无法做到。为了完成你想要的,您的应用程序需要做两件事:

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. 向网络运营商发送服务消息;和

  2. 更改设备上的本地时间。

这两个操作都需要系统级特权也就是说,您的应用程序需要使用系统密钥(即由Google向设备制造商发出)进行签名才能访问这些功能。

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.

可以从NTP服务器获取当前时间。互联网上有大量免费的NTP服务器。获取这样的时间的示例代码是:

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 = "server 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);

现在您的 cal 对象包含真实的时间,而不是从设备的时间。不过,您将无法将设备的时间设置为设备的当前时间。

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.

这篇关于以编程方式获取网络运营商的时间(android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆