如何获得网络提供的日期和时间没有互联网连接?

时间:2017-06-07 09:41:44

标签: java android android-timepicker networkmanager

我想在我的Android应用中使用网络提供的日期和时间,即使设备设置中的网络日期和时间已停用,并且没有互联网连接即可。有可能或有任何解决方案吗?

我提到this question,但我没有得到完美的解决方案。

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

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());

请勿忘记许可

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

答案 1 :(得分:0)

添加权限

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

如果确定有时间,请检查权限。

     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();
    }