问题
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.
回答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"/>
回答2:
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();
}
来源:https://stackoverflow.com/questions/44408988/how-to-get-network-provided-date-and-time-without-internet-connection