我从GPS获取当前日期和时间,但它给出了当前日期前3天的日期。在MyLocationListener类中loc.getTime();在当前日期前3天给我日期。我正在使用的代码
public class Location_gps extends Activity
{
Button btn;
LocationManager mlocManager;
LocationListener mlocListener;
Location loc;
SimpleDateFormat sdf;
Date d;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_gps);
btn = (Button)findViewById(R.id.btn);
/* Use the LocationManager class to obtain GPS locations */
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
loc = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
d = new Date(loc.getTime());
btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
String Text = "My current location is: " +
"\nLatitude = " + loc.getLatitude() +
"\nLongitude = " + loc.getLongitude() +
"\nAccuracy = " + loc.getAccuracy() +
"\nAltitude = " + loc.getAltitude() +
"\nProvider = " + loc.getProvider() +
"\nTime = " + sdf.format(d);
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
});
}
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"\nLatitude = " + loc.getLatitude() +
"\nLongitude = " + loc.getLongitude() +
"\nAccuracy = " + loc.getAccuracy() +
"\nAltitude = " + loc.getAltitude() +
"\nTime = " + loc.getTime();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
我如何从GPS获取当前日期和时间。请帮帮我。
答案 0 :(得分:2)
当您使用“getLastKnownLocation”方法时,它会返回自收到位置更新以来的最后一个参数。
loc = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
如果您的设备最近没有收到更新,它将返回您的案例过去3天的最后一次更新。如果无法接收gps更新,请检查您的“gps”是否已启用或在露天试用。
答案 1 :(得分:0)
这似乎是一个Android Bug ...请看一下以下内容:
http://www.zdnet.com/blog/hardware/the-time-displayed-on-most-android-phones-is-wrong/19387
答案 2 :(得分:0)
你应该使用NTP api而不是GPS。查看http://code.google.com/p/ntp-sync/和“Is Android using NTP to sync time?”。基本上在Android上搜索NTP。 NTP是所有设备,服务器和网络的网络时间协议标准。