LocationManager的基本用法

本文介绍了一个具体的Android应用示例,展示了如何通过LocationManager获取设备的地理位置信息,并利用Google Geocoding API进行反向地理编码,将经纬度转换为实际地址。

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

package com.example.locationmanagertest;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    
    private static final int SHOW_LOCATION=0;
    
    private TextView positionTextView;
    
    private LocationManager locationManager;
    
    private String provider;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        setView();
    }

    
    private void setView(){
        
        
        positionTextView=(TextView) findViewById(R.id.position_text_view);
        
        /**
         *获取 LocationManager实例
         *
         * */
        locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        
//        获取所偶位置提供器
        
        List<String> providerList=locationManager.getProviders(true);
        
        /**
         * Android 中一般有三种位置提供器可提供选择
         * 如下:
         * GPS_PROVIDER                精准度高   非常耗电
         * NETWORK_PROVIDER            精准度稍差  耗电量较少
         * PASSIVE_PROVIDER
         *
         *
         * 定位服务需要用户主动启动
         *
         * */
        if(providerList.contains(LocationManager.GPS_PROVIDER)){
            
            provider=LocationManager.GPS_PROVIDER;
            
        }else if(providerList.contains(LocationManager.NETWORK_PROVIDER)){
            provider=LocationManager.NETWORK_PROVIDER;
            
            
        }else{
            Toast.makeText(this, "no location provider to use", Toast.LENGTH_SHORT).show();
            return;
        }
        
        /**
         * Location对象包含了经度纬度海拔等一系列的位置信息;
         *
         * */
        Location location=locationManager.getLastKnownLocation(provider);
            
            
        if(location!=null){
            
            showLocation(location);
        }

        

        
        /**
         * 可以根据设备位置发生改变的时候获得到最新的位置
         * 第一个参数是位置提供器的类型
         * 第二个参数是监听位置变化的时间的位置毫秒为单位
         * 第三个参数是监听位置变化的距离间隔以米为单位
         * 第四个参数是LocationListener监听器
         *
         * LocationManager每隔5秒就会检测位置的变化情况,当移动距离超过10米的时候就会
         * 调用onLocationChanged()方法并把新的位置信息作为参数传入
         *
         * */
        
        locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
        
    }
    
    
    LocationListener locationListener=new LocationListener() {
        
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
            
        }
        
        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
            
        }
        
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            
        }
        
        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            showLocation(location);
        }
    };
    
    
    /**
     * 使用Geocoding Api进行反向地理编码的流程
     *
     * */
    
    private void showLocation(final Location location){
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try{
//                组装反向地理编码的借口地址
                StringBuffer url=new StringBuffer();    
                
                url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");
                url.append(location.getLatitude()).append(",");
                url.append(location.getLongitude());
                url.append("&sensor=false");
                HttpClient httpClient=new DefaultHttpClient();
                HttpGet httpGet=new HttpGet(url.toString());
//                在请求消息头中指定语言,保证服务器会返回中文数据
                httpGet.addHeader("Accept-Language", "zh-CN");
                HttpResponse httpResponse=httpClient.execute(httpGet);
                if(httpResponse.getStatusLine().getStatusCode()==200){
                HttpEntity entity=httpResponse.getEntity();
                String response=EntityUtils.toString(entity, "utf-8");
                
                JSONObject jsonObject=new JSONObject(response);
                JSONArray resultArrray=jsonObject.getJSONArray("results");
                if(resultArrray.length()>0){
                    JSONObject subObject=resultArrray.getJSONObject(0);
                    String address=subObject.getString("formatted_address");
                    Message message=new Message();
                    message.what=SHOW_LOCATION;
                    message.obj=address;
                    handler.sendMessage(message);
                }
                
                
                }
                
                
                }catch(Exception e){
                    
                }
                
                
                
                
            }
        });
            
    }
    
    
    private Handler handler=new Handler(){
        
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case SHOW_LOCATION:
                
                String currentPosition=(String) msg.obj;
                positionTextView.setText(currentPosition);
                break;

            default:
                break;
            }
            
        };
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        
        if(locationManager!=null){
            locationManager.removeUpdates(locationListener);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值