Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Automatic date&time" set on/off programmatically

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

like image 979
Akshay Patil Avatar asked Dec 11 '22 21:12

Akshay Patil


2 Answers

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" />

like image 72
Rahul Patil Avatar answered Dec 13 '22 11:12

Rahul Patil


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.

like image 22
John61590 Avatar answered Dec 13 '22 09:12

John61590