安卓修改系统时间

项目中遇到了使用 System.currentTimeMillis()获取的系统时间不准确,原因是我们的安卓设备的应用是运行一个局域网中(不能访问百度等互联网)的,于是需要自己的应用启动的时候同步一下系统的时间。

1. 应用需要拥有系统签名才能修改系统时间,于是我们找安卓设备供应商给自己的应用加上了系统签名。
2. 需要在Manifest添加如下两个权限:

<uses-permission
        android:name="android.permission.SET_TIME_ZONE" /> 
<uses-permission
        android:name="android.permission.SET_TIME"/>

3. 我们在自己的软件中通过接口获取服务器的时间戳,根据服务器的时间戳来修改安卓设备的时间,上代码:  

public static void doSetLocalTime(Context mContext, long time) {
        boolean is24Hour = DateFormat.is24HourFormat(mContext);
        if (!is24Hour) {
            android.provider.Settings.System.putString(mContext.getContentResolver(),
                    android.provider.Settings.System.TIME_12_24, "24");
        }
        try {
            boolean isAUTO_TIME_ZONE = android.provider.Settings.Global.getInt(mContext.getContentResolver(),
                    android.provider.Settings.Global.AUTO_TIME_ZONE) > 0;
            if (isAUTO_TIME_ZONE) {
                android.provider.Settings.Global.putInt(mContext.getContentResolver(),
                        android.provider.Settings.Global.AUTO_TIME_ZONE, 0);
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        try {
            boolean AUTO_TIME = android.provider.Settings.Global.getInt(mContext.getContentResolver(),
                    android.provider.Settings.Global.AUTO_TIME) > 0;
            if (AUTO_TIME) {
                android.provider.Settings.Global.putInt(mContext.getContentResolver(),
                        android.provider.Settings.Global.AUTO_TIME, 0);
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        if (time / 1000 < Integer.MAX_VALUE) {
            ((AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE)).setTimeZone("GMT+08:00");
            ((AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE)).setTime(time);
        }
    }

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值