-1

I created an android app that has to set device's time because the device cannot remember time. don't know how to set device's time.

Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy 
HH:mm:ss");
String formattedDate = df.format(c);

SharedPreferences time = getSharedPreferences("PREFS",0);

Date Time = null;
try {
    Time = df.parse(time.getString("time",""));
} catch (ParseException e) {
    e.printStackTrace();
}
if (Time == null)
{
    SharedPreferences.Editor editor = time.edit();
    editor.putString("time", formattedDate);
    editor.apply();
    Toast.makeText(MainActivity.this, formattedDate, 
    Toast.LENGTH_SHORT).show();
}
else
{
    try {
        if (Time.before(df.parse(formattedDate)))
        {
            SharedPreferences.Editor editor = time.edit();
            editor.putString("time", formattedDate);
            editor.apply();

            **** I want set device's time here from "time"
        }
        if (Time.after(df.parse(formattedDate)))
        {
            **** I want set device's time here from "time"
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

0

Add these lines inside your Manifest file to request permission:

<uses-permission android:name="android.permission.SET_TIME"
        tools:ignore="ProtectedPermissions" />
    <permission android:name="android.permission.SET_TIME" android:protectionLevel="signature|system"/>

And inside your java code:

Calendar c = Calendar.getInstance();
    c.set(year, month, day, hour, minutes, seconds);
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    am.setTime(c.getTimeInMillis());
Gratien Asimbahwe
  • 1,606
  • 4
  • 19
  • 30
  • After this I see error like this. E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]] droidRuntime: FATAL EXCEPTION: main Process: com.kakda.clock, PID: 6506 java.lang.SecurityException: setTime: Neither user 10526 nor current process has android.permission.SET_TIME. – Seng Chankakda Nov 26 '18 at 14:20
  • can you go to **settings->apps->choose your app->permissions** and add the permission to your app? – Gratien Asimbahwe Nov 26 '18 at 14:23
  • There has Calendar Permission in my app and I allowed it already but still doesn't work. – Seng Chankakda Nov 26 '18 at 14:26
  • okay I will create a sample project to test and let you know and/or update the answer accordingly. Thank you for the feedback – Gratien Asimbahwe Nov 26 '18 at 14:27
  • Yep, I'm waiting your sample. Thank you. – Seng Chankakda Nov 26 '18 at 14:28