This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

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

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();
    }

  • 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.

  • 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.

  • 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

  • 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

  • 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

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

  • 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

  • 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.