1

I want to use network provided date and time in my android application even if network date and time is disable in device setting and there is no internet connectivity. Is there any possibility or any solution?


I referred this question but I didn't get perfect solution.

Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
immodi
  • 607
  • 1
  • 6
  • 21

2 Answers2

1

You can try this:

String s1= android.provider.Settings.System.getString(this.getContentResolver(),
           android.provider.Settings.System.AUTO_TIME);
    if (s1.contentEquals("0")) {
        android.provider.Settings.System.putString(
                this.getContentResolver(),
                android.provider.Settings.System.AUTO_TIME, "1");
    }
    Date d1= new Date(System.currentTimeMillis());
    Log.e("finalvalue", d1.toString());

Don't forget to give permission

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
  • Its not possible to set permission.WRITE_SETTINGS in latest OS(tested with 7.0) . Only system app can use these permissions. – DAC84 Oct 21 '17 at 12:52
0

Add permission

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Check permission if ok get time.

     LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    Location location=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if(location!=null){
        long time = location.getTime();
    }
Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
  • thanks for your reply.I already tried your solution but I getting different time like this **06-07 15:23:03.548 1734-1734/com.abc.example E/myDate11: myDate:Thu Jun 07 15:22:57 GMT+05:30 2007** – immodi Jun 07 '17 at 10:00
  • This time may not be completely accurate. – Ahmad Aghazadeh Jun 07 '17 at 10:04
  • this actually return the time at which the location received... IF GPS is off for a long time, last know location will be different and corresponding time will aslo differ – DAC84 Oct 21 '17 at 12:15