30

我创建了一个应用程序,将当前显示时间替换为服务器时间。我已经尝试了很多,但我没有找到解决方案。如何将其设置到我的设备?

我知道如何在我的 Android 设备上获取服务器时间。是否可以实时进行,特别是在 Android 上?

  • 服务器时间在我的按钮单击事件中自动设置到我的设备。
4

4 回答 4

71

如果您有正确的权限(见下文),您可以使用AlarmManager. 例如,要将时间设置为 2013/08/15 12:34:56,您可以执行以下操作:

Calendar c = Calendar.getInstance();
c.set(2013, 8, 15, 12, 34, 56);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
am.setTime(c.getTimeInMillis());

您需要获得许可SET_TIME才能执行此操作。不幸的是,这是一个signatureOrSystem许可。

AndroidManifest.xml中的定义:

    <!-- Allows applications to set the system time -->
    <permission android:name="android.permission.SET_TIME"
        android:protectionLevel="signature|system"
        android:label="@string/permlab_setTime"
        android:description="@string/permdesc_setTime" />

唯一可以使用此权限的应用是:

  • 使用系统映像签名
  • 安装到/system/文件夹

除非您构建自定义 ROM,否则您对第一个 ROM 不走运。

第二,这取决于你在做什么。

  • 如果您正在构建一个广泛分发的应用程序(Google Play等),您可能不应该这样做。它只是 root 用户的一个选项,您只能手动安装它。任何市场都不会将其安装到正确的位置。

  • 如果您正在为自己构建一个应用程序(或者只是作为一个学习练习),那就去做吧。不过,您需要一部有根电话,所以请先这样做。然后,您可以/system/app/使用ADB或文件管理器直接安装应用程序。有关更多详细信息,请参阅此类文章。


最后一点:SET_TIME权限 和AlarmManager#setTime()是在 Android 2.2 ( API 8) 中添加的。如果您尝试在以前的版本上执行此操作,我不确定它是否会起作用。

编辑。利用

<uses-permission> instead of <permission>
于 2013-08-07T13:38:54.760 回答
12

尝试这个:

您可以使用下一个命令:

adb shell date -s YYYYMMDD.HHmmss

例子:

adb shell date -s 20120423.130000

将日期设置为 2012 年 4 月 23 日星期一 13:00:00 IST

或者你也可以试试这个:

startActivity(new Intent(android.provider.Settings.ACTION_DATE_SETTINGS));

希望能帮助到你!!

于 2013-08-07T12:03:09.787 回答
6

Short Answer:

You cannot do it if you plan to have your app in the appstore, or update the time to the server time.

You need SignatureOrSystem permission in order to change the time date as per the server.

You might have to root your device and then implement the change.

This thread should help you a lot, to better understand it.

于 2013-08-07T13:50:38.353 回答
-2

我已经做了两个星期完全一样的事情,现在我得到了一个有根设备的解决方案

  1. 获取服务器时间

<?php echo date("Ymd.His "); ?>

  1. 在您的 onClick 方法中

    Process loProcess = Runtime.getRuntime().exec("su"); DataOutputStream loDataOutputStream = new DataOutputStream(loProcess.getOutputStream()); //loDataOutputStream.writeBytes("date -s 20120419.124012; \n"); loDataOutputStream.writeBytes("date -s" + theStringReturnedValue+ "; \n");

请注意,StringReturnedValue 的格式必须为 20150216.124012,这与 php 中返回的格式相同

于 2015-02-16T17:04:26.640 回答