简单代码(根据安卓自带属性确定当前经纬度)

本文介绍了一个Android应用中如何实现位置服务,不仅展示了如何获取设备的经纬度坐标,还进一步通过Google API将坐标转换为易于理解的具体地址信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:


/ TODO: 2017-06-20 吴凯 
public class MainActivity extends AppCompatActivity {
    TextView txt_location;
    LocationManager locationManager;
    String location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt_location = (TextView) findViewById(R.id.position_location);
        //表示获取系统的哪一个服务
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的额位置提供器
        List<String> providerlist = locationManager.getProviders(true);
        if (providerlist.contains(LocationManager.GPS_PROVIDER)) {
            location = LocationManager.GPS_PROVIDER;
        } else if (providerlist.contains(LocationManager.NETWORK_PROVIDER)) {
            location = LocationManager.NETWORK_PROVIDER;
        } else {
            //当前没有可用的位置提供器
            Toast.makeText(this, "当前没有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return;
        }
        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;
        }
        Location locationmessage = locationManager.getLastKnownLocation(location);
        if (locationmessage != null) {
            //显示当前设备位置信息
            showlocation(locationmessage);
        }
        locationManager.requestLocationUpdates(location, 5000, 1, locationlistener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationManager != 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;
            }
            locationManager.removeUpdates(locationlistener);
        }
    }

    LocationListener locationlistener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //更新当前位置信息
            showlocation(location);
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    private void showlocation(Location locationmessage) {
        String currentposition = "经度  :" + locationmessage.getLatitude() + "\n" + "纬度 :" + locationmessage.getLongitude();
        txt_location.setText(currentposition);
    }
}

-------------------------===============================================================================================

上面是只显示经纬度,不过那普通人也是看不懂的呢,后来改进下为显示详细地址信息,利用到Google自己的api,给Google上传实时定位,进行网络数据处理,显示为准确地址如下

  // TODO: 2017-06-21 对于经纬度进行反向编译为我们熟悉的路径
    public static final int show_location = 0;

    private void showlocation(final Location locationmessage) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //组装反向地理编码接口地址
                    StringBuilder url = new StringBuilder();
                    url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");
                    url.append(locationmessage.getLatitude()).append(",");
                    url.append(locationmessage.getLongitude());
                    url.append("&sensor=false");
                   
                    HttpClient httpClient = new DefaultHttpClient();

                    HttpGet httpGet = new HttpGet(url.toString());
                    Log.e("url", "====" + url.toString());
                    //在请求中指定语音,保证服务器返回中文数据
                    httpGet.addHeader("Accept-Language", "zh-CN");

                    HttpResponse httpResponse = httpClient.execute(httpGet);
             
               
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        Log.e("222222222", "2222222222222222");
                        HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity, "utf-8");
                        JSONObject jsonObject = new JSONObject(response);
                        //获取results节点下的位置信息
                        JSONArray array_result = jsonObject.getJSONArray("results");
                        if (array_result.length() > 0) {
                            Log.e("33333333333", "33333333333333333333");
                            JSONObject subobject = array_result.getJSONObject(0);
                            //取出格式化后的位置信息
                            String address = subobject.getString("formatted_address");
                            Message message = new Message();
                            message.what = show_location;
                            message.obj = address;
                            handler.handleMessage(message);
                            Log.e("message", "===" + message);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case show_location:
                 
                    String currentposition = (String) msg.obj;
                    Log.e("currentposion", "=====" + currentposition);
                    txt_location.setText(currentposition);
                    break;
                default:
                    break;
            }
        }
    };
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值