• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

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

sma2277

Lurker
Apr 17, 2012
1
0




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


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
reply to the above one
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
reply to the above one
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
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
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones