Android 使用代码设置系统时间

本文介绍了一种简便的方法来获取root权限、设置时区,并调整系统时间,包括获取root权限的代码实现、设置时区的权限申请及代码、以及通过su执行命令调整时间的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看过其他的方法,感觉不方便,现贴出我的处理方法:


步骤为三步:

1、应用首先要申请获取root权限。代码如下:

/** 
	 * 请求root权限
	 * @return 应用程序是/否获取Root权限
	 */
	public static boolean requestRootPermission(String pkgCodePath) {
	    Process process = null;
	    DataOutputStream os = null;
	    try {
	        String cmd="chmod 777 " + pkgCodePath;
	        process = Runtime.getRuntime().exec("su"); //切换到root帐号
	        os = new DataOutputStream(process.getOutputStream());
	        os.writeBytes(cmd + "\n");
	        os.writeBytes("exit\n");
	        os.flush();
	        process.waitFor();
	    } catch (Exception e) {
	        return false;
	    } finally {
	        try {
	            if (os != null) {
	                os.close();
	            }
	            process.destroy();
	        } catch (Exception e) {
	        }
	    }
	    return true;
	}
注:pkgCodePath可以使用context的getPackageCodePath()方法获取。

2、设置时区。代码如下:

AlarmManager mAlarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		mAlarmManager.setTimeZone("GMT+09:00");
注:需要在AndroidManifest.xml文件中注明如下权限:<uses-permission android:name="android.permission.SET_TIME_ZONE"/>


3、成功获取root权限后,并设置好时区后,便可进行时间设置。代码如下:

/**
	 * 设置系统时间
	 * @param time 格式为“年月日.时分秒”,例如:20111209.121212
	 */
	public static boolean setTime(String time) {
	    Process process = null;
	    DataOutputStream os = null;
	    try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes("date -s " + time + "\n");
			os.writeBytes("exit\n");
	        os.flush();
	        process.waitFor();
		} catch (Exception e) {
			return false;
		} finally {
			try {
	            if (os != null) {
	                os.close();
	            }
	            process.destroy();
	        } catch (Exception e) {
	        }
		}
	    return true;
	}


So,   that's cool!


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值