How to set time to device programmatically
If you have the correct permission (see below), you can do this with the AlarmManager
. For example, to set the time to 2013/08/15 12:34:56, you could do:
Calendar c = Calendar.getInstance();
c.set(2013, 8, 15, 12, 34, 56);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
am.setTime(c.getTimeInMillis());
You need the permission SET_TIME
to do this. Unfortunately, this is a signatureOrSystem
permission.
Definition in AndroidManifest.xml:
<!-- Allows applications to set the system time -->
<permission android:name="android.permission.SET_TIME"
android:protectionLevel="signature|system"
android:label="@string/permlab_setTime"
android:description="@string/permdesc_setTime" />
The only apps that can use this permission are:
- Signed with the system image
- Installed to the
/system/
folder
Unless you build custom ROMs, you're out of luck with the first.
For the second, it depends on what you are doing.
-
If you're building an app for wide distribution (Google Play, etc.), you probably shouldn't. It's only an option for root users, and you'll only be able to install it manually. Any marketplace would not install it to the correct location.
-
If you're building an app for yourself (or just as a learning exercise), go for it. You'll need a rooted phone, though, so do that first. You can then install the application straight to
/system/app/
with ADB or a file manager. See articles like this for more detail.
One final note: The SET_TIME
permission and AlarmManager#setTime()
were added in Android 2.2 (API 8
). If you're trying to do this on a previous version, I'm not sure it will work at all.
Edit. use
<uses-permission> instead of <permission>
Try this:
You can use the next command:
adb shell date -s YYYYMMDD.HHmmss
Example:
adb shell date -s 20120423.130000
sets the date to Mon Apr 23 13:00:00 IST 2012
Or you can also try this:
startActivity(new Intent(android.provider.Settings.ACTION_DATE_SETTINGS));
Hope it Helps!!