2008年9月1日 星期一

在 Android 上更改與取得系統時區及時間

How to change and get the system timezone and clock settings on Android?

最近正在寫一個世界時鐘的程式,期間遇到幾個問題,花了好些功夫,還是沒有得到滿意的答案。分享出來,給其他遇到相似問題的網友,也看看有誰知道答案的。

取得系統時間

要得到目前的時間,這個倒是很容易,就是 System.currentTimeMillis()。不過要注意的是,這個函式傳回的是 UTC (GMT) 這個時區的時間,像台灣所在的時區是 UTC+8,你得將這個函式所傳回的值再加 8 個小時,才是你要的答案。實際上,當然不用自己加,你可以借用 Calendar 這個類別來幫你。

更改系統時間

要更改系統的時間,這可就難倒我了。在 m5 SDK 上,用 SystemClock.setCurrentTimeMillis(),雖然會有警告訊息,不過系統時間還是會被更改。到了 v0.9 SDK,這招就沒效了。掃過 Android 的原始程式,他們的確是用這個函式在更改系統時間。可是在我的程式裡,不管我加了那些 permission,都是給我個 Permission denied 錯誤。最好,只好在 這裡 發文問了這個問題,有個應該是 Google 的工程師,給了下面這個答案。

User apps cannot set the time. Only the system processes can. This is for security, but also because it won't have much effect--the time is reset from the radio via network time.

看了,要在 application 這一層更改系統時間,應該是沒解了。如果有人知道其他答案的,幫忙解答一下。

取得與更改系統時區

用 TimeZone.getDefault() 就可以取得當前的時區,如果你沒有特別設定的話,那你取到的,都是 GMT 這個時區。看起來,至少在 Windows 平台上, Android Emulator 還是不會正確決定當前的時區。目前我知道的唯一方法就是,在啟動 Emulator 的參數上,加上 -timezone "Asia/Taipei"。透過啟動 Emulator 的參數可以更改時區,那可以透過 API 來更改系統時區嗎?我試過 TimeZone.setDefault(TimeZone.getTimeZone("Asia/Taipei")),也用過 System.setProperty("user.timezone", "Asia/Taipei"),沒一個有效。所以看起來,也暫時無解。有誰知道如何透過 API 更改系統時區?

2 則留言:

samlu 提到...

關於更改系統時區的部份,終於問到答案了。答案如下:

Also, the recommended way to change timezone is through Settings app, which not not included in the current sdk ..
For now you can use the following:

AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setTimeZone(timezone);

It works with <uses-permission
android:name="android.permission.SET_TIME_ZONE"></uses-permission>

試了一下,果然沒問題。

傻傻 提到...

你們討論的是不是emulator的時間?
emlator的時間可以在emulator啟動後直接在上面調整, 如同在調電話.

張貼留言