版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q1183345443/article/details/82893362
##AlarmManager方式
/*****************************************************************************
Prototype : getAndroidSysteTime
Description : get android SystemTime
Input : None
Output : None
Return Value : public
Calls :
Called By :
History :
1.Date : 2018/9/28
Author :
Modification : Created function
*****************************************************************************/
public void getAndroidSysteTime(){
try {
int zone = (TimeZone.getDefault().getRawOffset()) / 3600000;
int mode = getHourMode();
if (mode != McuTimeInfo.ClockMode.INVALID.mode) {
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
int day = Calendar.getInstance().get(Calendar.DATE);
int hour = Calendar.getInstance().get(Calendar.HOUR);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
int second = Calendar.getInstance().get(Calendar.SECOND);
// 24小时制
if (McuTimeInfo.ClockMode.ROUND_HOUR.mode == mode) {
hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}
Log.d(TAG, "get android system time,zone:" + zone + ",mode: " + mode + "," + year + "/"
+ month + "/" + day + "," + hour + ":" + minute + ":"+ second);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/*****************************************************************************
Prototype : setAndroidSystemTime
Description : set android system time
Input : int mode
int year
int month
int day
int hour
int minute
int second
Output : None
Return Value : public
Calls :
Called By :
History :
1.Date : 2018/9/28
Author :
Modification : Created function
*****************************************************************************/
public void setAndroidSystemTime(int mode, int year, int month,
int day, int hour, int minute, int second){
Calendar c = Calendar.getInstance();
if (mode == Calendar.AM) {
c.set(Calendar.AM_PM, Calendar.AM);
} else {
c.set(Calendar.AM_PM, Calendar.PM);
}
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
c.set(Calendar.HOUR, hour);//HOUR_OF_DAY
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, second);
c.set(Calendar.MILLISECOND, 0);
long when = c.getTimeInMillis();
if (when / 1000 < Integer.MAX_VALUE) {
((AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE)).setTime(when);
}
}
###需要配置权限,并且app要具有系统权限
<uses-permission android:name="android.permission.SET_TIME" />
<uses-permission android:name="android.permission.SET_TIME_ZONE" />