public class MainActivity extends ActionBarActivity {
private LocationManager locationManager;
private String provider;
private MyLocationListener mylistener;
private Criteria criteria;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); //default
// user defines the criteria
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager.getLastKnownLocation(provider);
mylistener = new MyLocationListener();
if (location != null) {
mylistener.onLocationChanged(location);
} else {
// leads to the settings because there is no last known location
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// location updates: at least 1 meter and 200millsecs change
locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
String a=""+location.getLatitude();
Toast.makeText(getApplicationContext(), a, 222).show();
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// Initialize the location fields
Toast.makeText(MainActivity.this, ""+location.getLatitude()+location.getLongitude(),
Toast.LENGTH_SHORT).show()
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
Toast.LENGTH_SHORT).show();
}
}
6 回答
使用LocationManager .
对
getLastKnownLocation()
的调用不会阻止 - 这意味着如果当前没有位置,它将返回null
- 所以你可能想看看将LocationListener传递给requestLocationUpdates() method,这将为您提供位置的异步更新 .如果你想使用GPS,你需要给你的应用程序ACCESS_FINE_LOCATION permission .
您可能还想在GPS不可用时添加ACCESS_COARSE_LOCATION permission,并使用getBestProvider() method选择您的位置提供商 .
这是找到GPS位置的类
LocationFinder
. 这个类将调用MyLocation
,它将开展业务 .LocationFinder
MyLocation
随着
google
事情经常发生变化:以前的答案都不适用于我 .April 2016
基于this google training这里是你如何使用它
这需要设置Google Play服务
Activity class
usage
在你的活动中
而这种方法
你可以使用这个获得当前的latlng
`
`
上面的解决方案也是正确的,但是如果location为null,那么它会使应用程序崩溃或无法正常工作 . 获得android的Latitude和Longitude的最佳方法是:
@CommonsWare的答案对我有用但是我不得不修改
至