Android 如何获取用户的当前位置?
我用android做了一个应用程序。我必须找到用户的当前位置,即城市名称 我使用下面的代码,它可以生成纬度和经度,但没有得到城市的名称 我的代码是:Android 如何获取用户的当前位置?,android,geolocation,google-geocoder,Android,Geolocation,Google Geocoder,我用android做了一个应用程序。我必须找到用户的当前位置,即城市名称 我使用下面的代码,它可以生成纬度和经度,但没有得到城市的名称 我的代码是: public class GetCurrentLocation extends Activity implements OnClickListener { private LocationManager locationMangaer=null; private LocationListener locationListener=null;
public class GetCurrentLocation extends Activity implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
@Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,
locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----------Method to Check GPS is enable or disable ------------- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
公共类GetCurrentLocation扩展活动实现OnClickListener{
private LocationManager locationMangaer=null;
私有LocationListener LocationListener=null;
专用按钮btnGetLocation=null;
私有EditText editLocation=null;
private ProgressBar pb=null;
私有静态最终字符串TAG=“Debug”;
私有布尔标志=false;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//如果您想锁定屏幕为始终纵向模式
setRequestedOrientation(ActivityInfo.SCREEN\u ORIENTATION\u Picture);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(视图不可见);
editLocation=(EditText)findViewById(R.id.editTextLocation);
btnGetLocation=(按钮)findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(此);
locationMangaer=(LocationManager)getSystemService(Context.LOCATION\u服务);
}
@凌驾
公共void onClick(视图v){
flag=displayGpsStatus();
国际单项体育联合会(旗){
Log.v(标记“onClick”);
editLocation.setText(“请!!移动设备以查看坐标的变化。”+“\n等待…”);
pb.setVisibility(View.VISIBLE);
locationListener=新建MyLocationListener();
locationMangaer.RequestLocationUpdate(LocationManager.GPS_提供程序,5000,10,
位置(监听器);
}否则{
alertbox(“Gps状态!!”,“您的Gps处于关闭状态”);
}
}
/*----------检查GPS是否启用或禁用的方法----------------*/
私有布尔显示gpsstatus(){
ContentResolver ContentResolver=getBaseContext().getContentResolver();
布尔gpsStatus=Settings.Secure.isLocationProviderEnabled(
contentResolver、LocationManager、GPS\U提供商);
if(gpsStatus){
返回true;
}否则{
返回false;
}
}
/*----------创建AlertBox的方法----------------*/
受保护的void alertbox(字符串标题、字符串mymessage){
AlertDialog.Builder=新建AlertDialog.Builder(此);
setMessage(“您的设备的GPS已禁用”)
.setCancelable(错误)
.setTitle(“Gps状态**”)
.setPositiveButton(“Gps开启”,
新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int-id){
//完成当前活动
//AlertBoxAdvance.this.finish();
Intent myIntent=新的Intent(
设置。操作(安全设置);
星触觉(myIntent);
dialog.cancel();
}
})
.setNegativeButton(“取消”,
新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int-id){
//取消对话框
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
/*----------侦听器类以获取坐标----------------*/
私有类MyLocationListener实现LocationListener{
@凌驾
位置更改后的公共无效(位置loc){
editLocation.setText(“”);
pb.setVisibility(视图不可见);
Toast.makeText(getBaseContext(),“位置已更改:Lat:”+loc.getLatitude()
+“Lng:+loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude=“longitude:+loc.getLongitude();
Log.v(标签、经度);
String latitude=“latitude:+loc.getLatitude();
对数v(标签、纬度);
/*----------从坐标中获取城市名称----------------*/
字符串cityName=null;
Geocoder gcd=新的地理编码器(getBaseContext(),Locale.getDefault());
列出地址;
试试{
地址=gcd.getFromLocation(loc.getLatitude(),loc.getLatitude(),1);
如果(地址.size()>0)
System.out.println(addresses.get(0.getLocality());
cityName=addresses.get(0.getLocality();
}捕获(IOE){
e、 printStackTrace();
}
字符串s=经度+“\n”+纬度+”\n\n我的当前城市是:“+cityName;
editLocation.setText;
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
//TODO自动生成的方法存根
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
//TODO自动生成的方法存根
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
//TODO自动生成的方法存根
}
}
}
如何获取城市名称,即用户的当前位置(如德里、孟买等)?请尝试以下方法:
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
strReturnedAddress.append(returnedAddress.getLocality()).append("\n");
strReturnedAddress.append(areturnedAddress.getPostalCode()).append("\n");
strReturnedAddress.append(returnedAddress.getCountryName()).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
列表试试这个-
Geocoder geocoder = new Geocoder(getActivity(),Locale.ENGLISH);
StringBuilder stringBuilder = new StringBuilder();
List<Address> addressList;
try {
addressList = geocoder.getFromLocation(Latitude, Longitude, 1);
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Geocoder-Geocoder=新的地理编码器(getActivity(),Locale.ENGLISH);
StringBuilder StringBuilder=新的StringBuilder();
列表地址列表;
试一试{
addressList=geocoder.getFromLocation(纬度,经度,1);
如果(addressList.size()>0){
地址=地址列表。获取(0);
对于(int i=0;i<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />