Android获取当前城市名称

参考:残缺的孤独
txxs

不需要导入百度地图的SDK,利用手机自带的定位,获取当前的经纬度,然后调用百度地图的地址,返回的为json数据

{
status: "OK",
result: {
location: {
lng: 118.776047,
lat: 31.965235
},
formatted_address: "江苏省南京市雨花台区龙西路",
business: "铁心桥",
addressComponent: {
city: "南京市",
direction: "",
distance: "",
district: "雨花台区",
province: "江苏省",
street: "龙西路",
street_number: ""
},
cityCode: 315
}
}
//wd 纬度 
//jd 经度
   public void updateVersion(String wd, String jd) {
        String path = "http://api.map.baidu.com/geocoder?output=json&location=" + wd + "," + jd + "&key="这里为你的百度地图的key";
        OkHttpUtils
                .get()
                .url(path)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call arg0, Exception arg1, int arg2) {
                    }

                    @Override
                    public void onResponse(String arg0, int arg1) {
                        Gson gson = new Gson();
                        City response = gson.fromJson(arg0, City.class);
                        CMLog.d(TAG, arg0);
                        if (response.getStatus().equals("OK")) {
                            CMLog.d("地址为", response.getResult().getAddressComponent().getCity());
                        }
                    }

                });
    }


    public void getLocation() {
        String locationProvider;
        //获取地理位置管理器
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return;
        }
        //获取Location
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            //不为空,显示地理位置经纬度
            showLocation(location);
        }
        //监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
    }

    /**
     * 显示地理位置经度和纬度信息
     *
     * @param location
     */
    private void showLocation(Location location) {
        String locationStr = "纬度:" + location.getLatitude() + "\n"
                + "经度:" + location.getLongitude();
        updateVersion(location.getLatitude() + "", location.getLongitude() + "");
    }

    /**
     * LocationListern监听器
     * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
     */

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        public void onLocationChanged(Location location) {
            //如果位置发生变化,重新显示
            showLocation(location);
        }
    };

注意:别忘了加上权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>  
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
以下是一个获取当前位置并获取城市的异步线程的完整代码示例: ```java import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.util.List; import java.util.Locale; public class GetCityAsyncTask extends AsyncTask<Void, Void, String> { private Context mContext; private OnCityListener mListener; public GetCityAsyncTask(Context context, OnCityListener listener) { mContext = context; mListener = listener; } @Override protected String doInBackground(Void... voids) { String city = ""; try { LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses.size() > 0) { city = addresses.get(0).getLocality(); } } } catch (IOException e) { Log.e("GetCityAsyncTask", "IOException", e); } catch (Exception e) { Log.e("GetCityAsyncTask", "Exception", e); } return city; } @Override protected void onPostExecute(String city) { mListener.onCity(city); } public interface OnCityListener { void onCity(String city); } } ``` 在这个示例中,我们使用了`LocationManager`来获取设备的位置,并使用`Geocoder`将位置转换为可读的地址。然后,我们从地址中提取城市名称并将其返回给主线程。 使用此异步任务的示例代码如下: ```java GetCityAsyncTask task = new GetCityAsyncTask(MainActivity.this, new GetCityAsyncTask.OnCityListener() { @Override public void onCity(String city) { // 在此处处理城市名称 } }); task.execute(); ``` 在此处,我们创建了`GetCityAsyncTask`实例并调用`execute()`方法来启动异步任务。在任务完成后,将调用`onCity()`方法,该方法将城市名称作为字符串参数传递。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值