Button btn30 =(Button)findViewById(R.id.button30);
btn30.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// 判斷目前裝置是否提供 GPS 服務
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
try{
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location == null)
{
location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
Double latitude = location.getLatitude();
//經度
Double longitude = location.getLongitude();
Toast.makeText(getApplicationContext(), "Latitude:" + latitude + " Longitude:" + longitude, Toast.LENGTH_SHORT).show();
}catch (SecurityException e){
e.printStackTrace();
}
}
else
{
// 到設定請使用者開啟 GPS 服務
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
});
///在android 8.0版本中,捕获了经度和纬度,但它们均为NULL。
但是在android 5.0版本中,这些代码没问题。
(当前功能是通过单击按钮来获取经度和纬度。)
拥有注册权