修改安卓设备系统时间

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

  1. 我们的应用需要拥有系统签名才能修改系统时间,我们找设备供应商给自己的应用加上了系统签名。
  2. 需要在Manifest添加如下两个权限:
   
 
  1. 我们获取通过接口获取服务器的时间戳,根据服务器的时间戳来修改安卓设备的时间,上代码:
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);
        }
    }

你可能感兴趣的:(修改安卓设备系统时间)