• Join
  • Sign In with my.TI Login
Texas Instruments
  • Products
  • Applications
  • Tools & Software
  • Support & Community
  • Sample & Buy
  • About TI
Sample & Purchase Cart Sample & Purchase Cart
  • Search
  • Advanced
TI E2E™ Community
  • Support Forums
  • Blogs
  • Groups
  • Videos
  • 简体中文
  • More ...
TI Home » TI E2E Community » Support Forums » Embedded Software » Android » Android forum » How to set "SystemClock" time in Android pro-grammatically using "SystemClock.setCurrentTimeMillis(offsetValue)"
Share
Android
  • Forum
Options
  • Subscribe via RSS

Forums

How to set "SystemClock" time in Android pro-grammatically using "SystemClock.setCurrentTimeMillis(offsetValue)"

This question is not answered
Mahaboob Aslam
Posted by Mahaboob Aslam
on Apr 07 2012 04:12 AM
Intellectual330 points

Dear all,

Good Morning,

I am writing an application to get the following details from the Internet.

Time

Date

Day

From an NTP server.

Which i am getting perfect.

In the AndroidManifest.xml file  i have set the following properties

<uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.SET_TIME"/>
  <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
     <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
     <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
     <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />

The problem what i am facing is, i am  not able to set the time to the   "SystemClock"  using the following statement in my code

" SystemClock.setCurrentTimeMillis(offsetValue);"

when i do this,  i see in the system logs the following error

"Unable to open alarm driver: Permission denied"

on both the emulator and on the Target.


I have also pasted  the entire code of my application below:

Any help would be appreciated.

Regards

Aslam

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

NTPUDPClient client = new NTPUDPClient();
        Process p;
        //Runtime r = Runtime.getRuntime();

/*
        try {
            p = Runtime.getRuntime().exec("su");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }*/
        // client = new NTPUDPClient(); //
        System.out.println("after  calling NTPUDPClient client = new NTPUDPClient()");
        // We want to timeout if a response takes longer than 10 seconds
        client.setDefaultTimeout(10000); //
        try {
            System.out.println("before client.open()");
            /////////////////////////////////////////////////////////////////////////////////////
            client.open();// THIS IS THE PLACE WHERE IT IS THROWING THE EXCEPTION, I HAVE THE SAME CODE SAMPLE WRITTEN IN JAVA WHERE IT
            // WORKING FINE.
            /////////////////////////////////////////////////////////////////////////////////////
            System.out.println("after client.open()");
           // for (int i = 0; i < args.length; i++)//
           // {//
                System.out.println("entering into the 'try' blok");
                try {
                    //InetAddress hostAddr = InetAddress.getByName(args[i]); // 182.79.254.202
                     InetAddress hostAddr = InetAddress.getByName("182.79.254.202");
                     System.out.println("getting the HostAddress and Host Nae");
                     System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());//
                    TimeInfo info = client.getTime(hostAddr);
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////
                    NtpV3Packet message = info.getMessage();
                    int stratum = message.getStratum();
                    String refType;             
                    
                    if (stratum <= 0) {
                        refType = "(Unspecified or Unavailable)";
                    } else if (stratum == 1) {
                        refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
                    } else {
                        refType = "(Secondary Reference; e.g. via NTP or SNTP)";
                    }
                    // System.out.println(" Stratum: " + stratum + " " + refType); //
                    int version = message.getVersion();
                    int li = message.getLeapIndicator();
                    System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision());//

                  System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");//
                    int poll = message.getPoll();
                    // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
                    System.out.println(" poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll))+ " seconds" + " (2 ** " + poll + ")");//
                    double disp = message.getRootDispersionInMillisDouble();
                    System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())+ ", rootdispersion(ms): " + numberFormat.format(disp));//
                    int refId = message.getReferenceId();
                    String refAddr = NtpUtils.getHostAddress(refId);
                    String refName = null;
                    String timeStamp = null;
                    if (refId != 0) {
                        if (refAddr.equals("127.127.1.0")) {
                            refName = "LOCAL"; // This is the ref address for the Local Clock
                        } else if (stratum >= 2) {
                            // If reference id has 127.127 prefix then it uses its own reference clock
                            // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
                            // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
                            if (!refAddr.startsWith("127.127")) {
                                try {
                                    InetAddress addr = InetAddress.getByName(refAddr);
                                    String name = addr.getHostName();
                                    if (name != null && !name.equals(refAddr)) {
                                        refName = name;
                                    }
                                } catch (UnknownHostException e) {
                                    // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2)
                                    // ref not valid host maybe it's a reference clock name?
                                    // otherwise just show the ref IP address.
                                    refName = NtpUtils.getReferenceClock(message);
                                }
                            }
                        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
                            refName = NtpUtils.getReferenceClock(message);
                            // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
                        }
                    }
                    if (refName != null && refName.length() > 1) {
                        refAddr += " (" + refName + ")";
                    }
                    System.out.println(" Reference Identifier:\t" + refAddr);//

                    TimeStamp refNtpTime = message.getReferenceTimeStamp();//
                   System.out.println(" Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());//

                    // Originate Time is time request sent by client (t1)
                    TimeStamp origNtpTime = message.getOriginateTimeStamp();//
                    System.out.println(" Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString());//

                    long destTime = info.getReturnTime();//
                    // Receive Time is time request received by server (t2)
                    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();//
                   System.out.println(" Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());//

                    // Transmit time is time reply sent by server (t3)
                    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();//
                    System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString());//

                    // Destination time is time reply received by client (t4)
                    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);//
                   System.out.println(" Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString());//
                    
                    
                   // timeStamp = destNtpTime.toDateString();
                    timeStamp = xmitNtpTime.toDateString(); //
                    TextView tv = new TextView(this);
                    
                    info.computeDetails(); // compute offset/delay if not already done
                    Long offsetValue = info.getOffset();
                    Long delayValue = info.getDelay();
                    String delay = (delayValue == null) ? "N/A" : delayValue.toString();
                    String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

                    System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset in ms
                    tv.setText(timeStamp);
                    setContentView(tv);
                    try {
                        p = Runtime.getRuntime().exec("su");
                        
                    
                    SystemClock.setCurrentTimeMillis(offsetValue); //
                    final Calendar cal = Calendar.getInstance();//
                    cal.setTimeInMillis(offsetValue);//
                try {
                        p.waitFor();
                            if(p.exitValue()!= 255){
                                System.out.println("root permission \n");
                                }
                            else{
                                System.out.println("No root permission \n");
                                }
                        //}
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    
                   // processResponse(info);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
          //  }//
        } catch (SocketException e) {//SocketException(String msg)
       // catch (SocketException(String msg)){
            e.printStackTrace();
        //System.out.println(msg);
        }
        //setContentView(tv);
        client.close();
    }

android BeagleBoard-XM Android Froyo Eclair GingerBread_2_3_4_DevKit_2_1 BeagleBoard-XM Android
Report Abuse
  • Reply
You have posted to a forum that requires a moderator to approve posts before they are publicly available.
All Replies
  • Vishveshwar Bhat
    Posted by Vishveshwar Bhat
    on Apr 09 2012 02:08 AM
    Genius9580 points

    Why don't you put your query at one of the android developer communities? http://developer.android.com/resources/community-groups.html

    You are more likely to get answers there.

    ---------------------------------------------------------------------------------------------------------

    Please click the Verify Answer button on this post if it answers your question.
    ---------------------------------------------------------------------------------------------------------

    Report Abuse
    • Reply
    You have posted to a forum that requires a moderator to approve posts before they are publicly available.
  • Chris Westervelt
    Posted by Chris Westervelt
    on Apr 09 2012 09:17 AM
    Intellectual430 points

    We had the same problem which isn't really a problem at all once you understand Android security.  Simply put, you have to manually sign your APK file with the signature created by the compiler when you build your Android rootfs.  Please look up signing an Android app with the system APK.  These are highly restricted permissions that can only be allowed to system apps.

    Report Abuse
    • Reply
    You have posted to a forum that requires a moderator to approve posts before they are publicly available.
  • Mahaboob Aslam
    Posted by Mahaboob Aslam
    on Apr 10 2012 01:48 AM
    Intellectual330 points

    Dear Chris,

    Thanks for the reply, could you please let me know in details how to do the signing process in step by step i am new to this Android programming

    waiting for you reply.

    Regards

    Aslam

    Report Abuse
    • Reply
    You have posted to a forum that requires a moderator to approve posts before they are publicly available.
  • Mahaboob Aslam
    Posted by Mahaboob Aslam
    on Apr 17 2012 04:22 AM
    Intellectual330 points

    Dear all

    As per your last reply  i have build the appliclation with system sign and changed some of the properties in the Androidmanifest.xml file in my code.

    know i see that i am not getting this following error.

    "Unable to open alarm driver: Permission denied"

    but still the return value of setCurrentTimeMillis() is "false" in the logcat.

    and i am not able to set the SystemClock.


    I have included the following code in BroadcastReceivermy source to see that event trigger.


     protected void onResume() {
            super.onResume();
            
           //// getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

           // ((CheckBoxPreference)mTime24Pref).setChecked(is24Hour());

            // Register for time ticks and other reasons for time change
            IntentFilter filter = new IntentFilter();
           // filter.addAction(Intent.ACTION_TIME_TICK);
            filter.addAction(Intent.ACTION_TIME_CHANGED);
            filter.addAction(Intent.ACTION_DATE_CHANGED);
            filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
            registerReceiver(mIntentReceiver, filter, null, null);
            System.out.println("protected void onResume() \n");
            //updateTimeAndDateDisplay();
        }
        
        @Override
        protected void onPause() {
            super.onPause();
            unregisterReceiver(mIntentReceiver);
           // getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
            System.out.println("protected void onPause \n");
        }
        
        private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
               // updateTimeAndDateDisplay();
                System.out.println("protected void onReceive() zzz\n");
                String action = intent.getAction();
              if ( action.equals(Intent.ACTION_TIMEZONE_CHANGED) || action.equals(Intent.ACTION_TIME_CHANGED) || action.equals(Intent.ACTION_DATE_CHANGED))
              {
                  System.out.println("protected void onReceive() \n");
              }
                
            }
        };

    When this event management code is added into the application ,BroadcastReceiver:: onReceive () should be called, to see that the time has been set.

    but in my case i see that no "Protected void onReceive()" print is beeing printed.

    And the return value of setCurrentTimeMillis() is FALSE.

    this above code i have added seeing into DateTimeSettings.java file in "Settings" application of the Android 2.3.3 source code.

    Please help me out.

    REgards

    Aslam

    Report Abuse
    • Reply
    You have posted to a forum that requires a moderator to approve posts before they are publicly available.
  • Mahaboob Aslam
    Posted by Mahaboob Aslam
    on Apr 17 2012 04:23 AM
    Intellectual330 points

    Dear all

    As per your last reply  i have build the appliclation with system sign and changed some of the properties in the Androidmanifest.xml file in my code.

    know i see that i am not getting this following error.

    "Unable to open alarm driver: Permission denied"

    but still the return value of setCurrentTimeMillis() is "false" in the logcat.

    and i am not able to set the SystemClock.


    I have included the following code in BroadcastReceivermy source to see that event trigger.


     protected void onResume() {
            super.onResume();
            
           //// getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

           // ((CheckBoxPreference)mTime24Pref).setChecked(is24Hour());

            // Register for time ticks and other reasons for time change
            IntentFilter filter = new IntentFilter();
           // filter.addAction(Intent.ACTION_TIME_TICK);
            filter.addAction(Intent.ACTION_TIME_CHANGED);
            filter.addAction(Intent.ACTION_DATE_CHANGED);
            filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
            registerReceiver(mIntentReceiver, filter, null, null);
            System.out.println("protected void onResume() \n");
            //updateTimeAndDateDisplay();
        }
        
        @Override
        protected void onPause() {
            super.onPause();
            unregisterReceiver(mIntentReceiver);
           // getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
            System.out.println("protected void onPause \n");
        }
        
        private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
               // updateTimeAndDateDisplay();
                System.out.println("protected void onReceive() zzz\n");
                String action = intent.getAction();
              if ( action.equals(Intent.ACTION_TIMEZONE_CHANGED) || action.equals(Intent.ACTION_TIME_CHANGED) || action.equals(Intent.ACTION_DATE_CHANGED))
              {
                  System.out.println("protected void onReceive() \n");
              }
                
            }
        };

    When this event management code is added into the application ,BroadcastReceiver:: onReceive () should be called, to see that the time has been set.

    but in my case i see that no "Protected void onReceive()" print is beeing printed.

    And the return value of setCurrentTimeMillis() is FALSE.

    this above code i have added seeing into DateTimeSettings.java file in "Settings" application of the Android 2.3.3 source code.

    Please help me out.

    REgards

    Aslam

    Report Abuse
    • Reply
    You have posted to a forum that requires a moderator to approve posts before they are publicly available.
  • Suchit Bhatt
    Posted by Suchit Bhatt
    on Jan 29 2013 09:15 AM
    Prodigy130 points

    I have same problem any idea about this to overcome this error .? and how to  build the appliclation with system sign?

    Report Abuse
    • Reply
    You have posted to a forum that requires a moderator to approve posts before they are publicly available.
  • Manuel Contreras
    Posted by Manuel Contreras
    on Jan 29 2013 12:22 PM
    Expert8455 points

    You can try by calling Settings.System object, in this case you have access to more properties that defines how System's clock works.

    http://developer.android.com/reference/android/provider/Settings.System.html

    You can find some comments in Android source code about it's use in next file too, location could change depending on release but it should be in the same location.

    /mydroid/packages/apps/Settings/src/com/android/settings/DateTimeSettings.java

    After checking the manifest for Settings application there are some permissions that could be needed, you need to check it,

        <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
        <uses-permission android:name="android.permission.WRITE_SETTINGS" />
        <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
        <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
        <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />

    And check that actual documentation in developer.android.com is applicable to recent releases and you are using Android 2.3.3, next link provides a way to match Android releases with used Android SDKs. Other way is to check the documentation directory in Android source code for used release.

    http://source.android.com/source/build-numbers.html

    You can sign the .apk by doing right-click in the Eclipse's projects tree and selecting sign, the other option is to use command line using information from next link.

    http://developer.android.com/tools/publishing/app-signing.html

    Please click the Verify Answer button on this post if it answers your question
    _______________________________________________________
    Be sure to read the OMAP4 and OMAP5 Forum Guidelines and FAQ
    Report Abuse
    • Reply
    You have posted to a forum that requires a moderator to approve posts before they are publicly available.
  • Manuel Contreras
    Posted by Manuel Contreras
    on Jan 29 2013 13:04 PM
    Expert8455 points

    You may need to check about AUTO_TIME value, when it is enabled in settings all the other fields are grayed or disabled, for what I read is because system updates clock via mobile network by default. If you have issues setting the time and then disabling AUTO_TIME when system restarts and time is different, try next patch

    http://review.omapzoom.org/#/c/30839/

    it is for OMAP4 source code, but it should apply to ok in Rowboat.

    I am commenting this because I am not sure if you are developing a application in general or part of a system development, in case you are developing an application you will not have access to modify the kernel, then you will need to check if you are seeing this issue or not by updating the system's clock with this AUTO_TIME enabled.

    Issue could not be present.

    Please click the Verify Answer button on this post if it answers your question
    _______________________________________________________
    Be sure to read the OMAP4 and OMAP5 Forum Guidelines and FAQ
    Report Abuse
    • Reply
    You have posted to a forum that requires a moderator to approve posts before they are publicly available.
TI E2E™ Community
  • Support Forums
  • Blogs
  • Videos
  • Groups
  • Site Support & Feedback
  • Settings
TI E2E™ Community Groups
  • TI University Program
  • Make the Switch
  • Microcontroller Projects
  • Motor Drive & Control
Other Communities
  • Deyisupport
  • Designsomething.org
  • beagleboard.org
  • TI on Element 14
  • TI on TechXchangeSM
Other Technical & Support Resources
  • WEBENCH® Design Center
  • Product Information Centers
  • Technical Documents
  • TI Design Network
  • TI Technical Articles
  • TI Training

All content and materials on this site are provided "as is". TI and its respective suppliers and providers of content make no representations about the suitability of these materials for any purpose and disclaim all warranties and conditions with regard to these materials, including but not limited to all implied warranties and conditions of merchantability, fitness for a particular purpose, title and non-infringement of any third party intellectual property right. TI and its respective suppliers and providers of content make no representations about the suitability of these materials for any purpose and disclaim all warranties and conditions with respect to these materials. No license, either express or implied, by estoppel or otherwise, is granted by TI. Use of the information on this site may require a license from a third party, or a license from TI.

Content on this site may contain or be subject to specific guidelines or limitations on use. All postings and use of the content on this site are subject to the Terms of Use of the site; third parties using this content agree to abide by any limitations or guidelines and to comply with the Terms of Use of this site. TI, its suppliers and providers of content reserve the right to make corrections, deletions, modifications, enhancements, improvements and other changes to the content and materials, its products, programs and services at any time or to move or discontinue any content, products, programs, or services without notice.

Follow Us Texas Instruments on Facebook Texas Instruments on Twitter Texas Instruments on LinkedIn Texas Instruments on Google+
TI Worldwide | Contact Us | my.TI Login | Site Map | Corporate Citizenship | mobile m.ti.com (Mobile Version)

TI is a global semiconductor design and manufacturing company. Innovate with 100,000+ analog ICs and
embedded processors, along with software, tools and the industry’s largest sales/support staff.

© Copyright 1995-2013 Texas Instruments Incorporated. All rights reserved.
Trademarks | Privacy Policy | Terms of Use