系统级应用设置系统时间和时区

系统级应用设置系统时间和时区

1.直接根据时间戳设置系统时间,此方法简单,但是只能去设置时间:

SystemClock.setCurrentTimeMillis(long time)

2.此方法需要注意,系统应用还需要具备Root权限,能够直接在应用内写SU命令:

//curr_time 格式:MMddHHmmyyyy.ss    例:020110302018.35
    public static void setSystemTime(Context context, String curr_time) {
        try{
            AlarmManager mAlarmManager = (AlarmManager)
                    context.getSystemService(Context.ALARM_SERVICE);
                    //此处就是设置时区
            mAlarmManager.setTimeZone("Asia/Shanghai"); // Asia/Shanghai//GMT+08:00
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            LogUtils.i("系统设置 开始同步服务器时间");
            execSuCmd22("date " + curr_time
                    + "\n busybox hwclock -w\n");

        } catch (Exception e) {
            LogUtils.i("系统设置 同步服务器时间失败");
            e.printStackTrace();
        }
    }


/**
     * 执行Android命令
     *
     * @param cmd 命令
     */
    public static void execSuCmd22(String cmd) {
        Process process = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            int aa = process.waitFor();
            is = new DataInputStream(process.getInputStream());
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            String out = new String(buffer);
        } catch (Exception e) {
            Log.i("88888888", "88888888  同步服务器时间失败");
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (process != null) {
                    process.destroy();
                }

            } catch (Exception e) {
            }
        }
        LogUtils.i("同步服务器时间成功");
    }

本篇完,仅一个功能点共享。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值