安卓---通过获得的经纬度获得城市名称

本程序首先获得当前位置的经纬度,然后根据经纬度获得当前所在的城市名,经检测可以获得本人所在的汉中市。
java代码:

public class MainActivity extends AppCompatActivity {

    private TextView showInfo = null,tv=null;
    private LocationManager locationManager = null;
    private String provider = null;
    private LocationListener locationListener = null;
    private List<String> list = null;
    private Location loca = null;
    private StringBuilder strbl = null;
    private double jing, wei;
    private String country="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showInfo = (TextView) findViewById(R.id.showInfo);
        tv=(TextView)findViewById(R.id.tv);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        provider = LocationManager.GPS_PROVIDER;
        loca=locationManager.getLastKnownLocation(provider);
        if (loca != null) {

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }

            update(loca);
        }else{
            Toast.makeText(MainActivity.this, "GPS定位不可用,即将尝试网络定位", Toast.LENGTH_SHORT).show();
            provider=LocationManager.NETWORK_PROVIDER;
            loca=locationManager.getLastKnownLocation(provider);
            if(loca!=null){


                update(loca);
            }else{

                Toast.makeText(MainActivity.this, "网络定位不可用,即将尝试下一个定位方式", Toast.LENGTH_SHORT).show();

                provider=LocationManager.PASSIVE_PROVIDER;
                loca=locationManager.getLastKnownLocation(provider);
                if(loca!=null){

                    update(loca);
                }else{

                    Toast.makeText(MainActivity.this, "当前没有可以使用的定位方式", Toast.LENGTH_SHORT).show();
                }
            }
        }




        }





    private void update(Location location) {

            if(location!=null) {
                strbl = new StringBuilder();
                strbl.append("实时位置信息:\n");
                strbl.append("经度:    ");
                strbl.append(location.getLongitude());
                strbl.append("\n纬度:    ");
                strbl.append(location.getLatitude());
                strbl.append("\n高度:    ");
                strbl.append(location.getAltitude());
                strbl.append("\n速度:    ");
                strbl.append(location.getSpeed());
                strbl.append("\n方向:    ");
                strbl.append(location.getBearing());
                showInfo.setText(strbl.toString());

                //获得经纬度
                jing = location.getLongitude();
                wei = location.getLatitude();
               Geocoder geocoder=new Geocoder(this);
                List<Address> list=null;
                try {
                    list= geocoder.getFromLocation(wei,jing,1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(list!=null && list.size()>0){

                    for (int i=0;i<list.size();i++) {
                        if (list.get(i) != null) {
                            Address address = list.get(i);

                            country += address.getCountryName() + ";" + address.getLocality();
                        }
                    }
                }
                System.out.println("获得的城市名"+country);

                tv.setText(country);

            }else{

                showInfo.setText("传递的值为空,无法获取位置信息");
            }

}



}

布局代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="zyf.com.locationinfo.MainActivity">

    <TextView
        android:id="@+id/showInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="经纬度"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv"
        android:hint="城市名"
        />
</LinearLayout>


问题探讨:

在获取当前的经纬度的时候,使用了昨天的代码,发现程序并不能根据设置的时间间隔来打印所在的经纬度!尚且不明原因!如有网友知道,求教!

以下是一个获取当前位置并获取城市的异步线程的完整代码示例: ```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()`方法,该方法将城市名称作为字符串参数传递。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值