I need to set current date & time from network provider or gps provider, I have tried this but not worked
String timeSettings = android.provider.Settings.System.getString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME);
if (timeSettings.contentEquals("0")) {
android.provider.Settings.System.putString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME, "1");
}
timeSettings = android.provider.Settings.System.getString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME);
And permission
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
But not working, Please tell what is going wrong and please tell if have any other solution
Only system apps can set the values , the installed application cannot change even though it has permissions.
The code to read if auto time pref is checked
Settings.Global.getInt(getContentResolver(), Settings.Global.AUTO_TIME)
The code to read if auto time zone pref is checked
Settings.Global.getInt(getContentResolver(), Settings.Global.AUTO_TIME_ZONE)
You can ask user to set if they are OFF.
You can set time and time zone programmatically , by reading the required values .
The following is the code to set time
long now = // time set from timepicker or servertime
int year, month, day; // from timepicker
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setTime(now);
Permission required : <uses-permission android:name="android.permission.SET_TIME" />
As an updated answer, this works with Settings.Global
:
@RequiresPermission("android.permission.WRITE_SETTINGS")
public void setSettingsAutomaticDateTimeIfNeeded() {
String timeSettings = android.provider.Settings.Global.getString(
this.getContentResolver(),
android.provider.Settings.Global.AUTO_TIME);
if (timeSettings.contentEquals("0")) {
android.provider.Settings.Global.putString(
this.getContentResolver(),
android.provider.Settings.Global.AUTO_TIME, "1");
}
}
Tested in October 2018.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With