How to get network provided date and time without internet connection?

天大地大妈咪最大 提交于 2021-02-07 10:29:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!