Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set time to device programmatically

I have created one application that replace the current showing time with server time. I have tried a lot, but I didn't find a solution. How can I set it to my device?

I know how to get the server time on my Android device. Is it possible in real time, specially on Android?

  • Server Time is automatically set to my device on my button click event.
like image 838
Sanket Shah Avatar asked Jul 30 '13 06:07

Sanket Shah


People also ask

How to Set time in android programmatically?

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.

How do I set the date and time in Android Studio?

You can use the SimpleDateFormat class for formatting date in your desired format. Just check this link where you get an idea for your example. For example: String dateStr = "04/05/2010"; SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); Date dateObj = curFormater.


1 Answers

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> 
like image 199
Geobits Avatar answered Oct 05 '22 16:10

Geobits