如何以编程方式设置设备时间 [英] How to set time to device programmatically

查看:44
本文介绍了如何以编程方式设置设备时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created one application that replace the current showing time with server time. I have tried a lot, but I didn't find a solution. How can I set it to my device?

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

I know how to get the server time on my Android device. Is it possible in real time, specially on Android?

  • 服务器时间会在我的按钮点击事件中自动设置为我的设备.

推荐答案

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

If you have the correct permission (see below), you can do this with the AlarmManager. For example, to set the time to 2013/08/15 12:34:56, you could do:

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许可.


You need the permission SET_TIME to do this. Unfortunately, this is a signatureOrSystem permission.

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" />


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


The only apps that can use this permission are:

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

除非您构建自定义 ROM,否则第一个您就不走运了.

Unless you build custom ROMs, you're out of luck with the first.

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

For the second, it depends on what you are doing.

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

  • If you're building an app for wide distribution (Google Play, etc.), you probably shouldn't. It's only an option for root users, and you'll only be able to install it manually. Any marketplace would not install it to the correct location.

如果您正在为自己构建应用程序(或仅作为学习练习),那就去做吧.不过,您将需要一部有 root 权限的手机,所以请先这样做.然后,您可以使用 ADB/system/app/> 或文件管理器.请参阅文章此类了解更多信息细节.

If you're building an app for yourself (or just as a learning exercise), go for it. You'll need a rooted phone, though, so do that first. You can then install the application straight to /system/app/ with ADB or a file manager. See articles like this for more detail.

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

One final note: The SET_TIME permission and AlarmManager#setTime() were added in Android 2.2 (API 8). If you're trying to do this on a previous version, I'm not sure it will work at all.

编辑.使用

<uses-permission> instead of <permission>

这篇关于如何以编程方式设置设备时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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