Android實踐 -- 設置系統日期時間和時區


設置系統日期時間和時區

設置系統的日期時間和時區,需要 系統權限和系統簽名android:sharedUserId="android.uid.system"
需要在manifest文件中添加相應的權限

  <uses-permission android:name="android.permission.WRITE_SETTINGS"/> <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
  • 判斷系統使用的是24小時制還是12小時制

    boolean is24Hour = DateFormat.is24HourFormat(mContext);
  • 設置系統的小時制

24小時制

  android.provider.Settings.System.putString(mContext.getContentResolver(), android.provider.Settings.System.TIME_12_24, "24");

12小時制

  android.provider.Settings.System.putString(mContext.getContentResolver(), android.provider.Settings.System.TIME_12_24, "12");
  • 判斷系統的時區是否是自動獲取的

    public boolean isTimeZoneAuto(){ try { return android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.AUTO_TIME_ZONE) > 0; } catch (SettingNotFoundException e) { e.printStackTrace(); return false; } }
  • 設置系統的時區是否自動獲取

    public void setAutoTimeZone(int checked){ android.provider.Settings.Global.putInt(mContext.getContentResolver(), android.provider.Settings.Global.AUTO_TIME_ZONE, checked); }
  • 判斷系統的時間是否自動獲取的

    public boolean isDateTimeAuto(){ try { return android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.AUTO_TIME) > 0; } catch (SettingNotFoundException e) { e.printStackTrace(); return false; } }
  • 設置系統的時間是否需要自動獲取

    public void setAutoDateTime(int checked){ android.provider.Settings.Global.putInt(mContext.getContentResolver(), android.provider.Settings.Global.AUTO_TIME, checked); }
  • 設置系統日期

    參考系統Settings中的源碼

    public void setSysDate(int year,int month,int day){ Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, month); c.set(Calendar.DAY_OF_MONTH, day); long when = c.getTimeInMillis(); if(when / 1000 < Integer.MAX_VALUE){ ((AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE)).setTime(when); } }
  • 設置系統時間

    參考系統Settings中的源碼

    public void setSysTime(int hour,int minute){ Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, hour); c.set(Calendar.MINUTE, minute); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); long when = c.getTimeInMillis(); if(when / 1000 < Integer.MAX_VALUE){ ((AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE)).setTime(when); } }
  • 設置系統時區

    public void setTimeZone(String timeZone){ final Calendar now = Calendar.getInstance(); TimeZone tz = TimeZone.getTimeZone(timeZone); now.setTimeZone(tz); }
  • 獲取系統當前的時區

    public String getDefaultTimeZone(){ return TimeZone.getDefault().getDisplayName(); }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM