Android--获取位置信息

获取所在位置首先要了解LocationManager类可以实现,那么我们来看看LocationManager的用法吧。
    1. 根据官方文档我们可以看出获取 实例通过 getSystemService(Context.LOCATION_SERVICE).
     LocationManager locationManager=(LocationManager)getSystemService(Context.LOCATION_LOCATION_SERVICE);
     Android中的位置提供器一般有GPS.PROVIDER,NETWORK_PROVIDER和PASSIVE_PROVIDER。一般用的最多的是前两种,GPS定位的精准度较高,但是耗电量大,速度较慢;网络定位的精准度较差,但耗电量较少。(经过使用认为网络定位较快)
    2.获取 Location对象,使用 getLastKnownLocation();将提供器传入此方法中。
       String provider=LocationManager.NETWORK_PROVIDER;
       Location location=locationManager.getLastKnownLocation(provider);
      如果不知道中的定位功能是否开启,可以先判断有哪些位置提供器可用
         List<String> providerList=locationManager.getProvider(true);
     3.当设备 随时移动时,更新位置,用 requestLocationUpdates()方法,设置监听器 LocationListener
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,10,new LocationListener(){
           .................
            ..................
            @override
           public void onLocationChangerd(Location location)

       });//第一个参数位置提供器,第二个参数没隔多久刷新一次,第三个参数移动几米刷新位置变化,第四个参数监听器
    4.获取的位置信息为经纬度,海拔等位置信息,我们需要反向地理编码,用到 Geocoding API
          反向地理编码的接口:http://maps.googleapis.com/maps/api/geocode/ json?latlng=x,y&sensor=true_or_false
           json指服务器返回JSON格式的数据;x,y是给服务器解码的经纬值;sensor=true_or_false为请求是否来自与某个设备的位置传感器,一般用false
            更多使用请参考官方文档:https://developers.google.com/maps/documentation/geocoding
   5.经纬度 解析步骤
      发送HTTP请求给服务器
      对返回的JSON数据进行解析
     显示位置信息
  6.代码
      activity_main.xml
<RelativeLayout 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: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="com.example.locationtest.MainActivity" >

<TextView
android:id="@+id/position_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

</RelativeLayout>
     MainActivity.java
package com.example.locationtest;
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.content.Context;
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.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;



public class MainActivity extends AppCompatActivity {
public static final int SHOW_LOCATION=0;
private TextView positionTextView;
private LocationManager locationManager;
private String provider;
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 onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
positionTextView=(TextView)findViewById(R.id.position_text_view);
//获取LocationManager类实例,参数用于确定获取系统中的哪个服务
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);

//获取所有的可用的位置提供器
List<String> providerList=locationManager.getProviders(true);
if(providerList.contains(LocationManager.NETWORK_PROVIDER)){
provider=LocationManager.NETWORK_PROVIDER;
}else if(providerList.contains(LocationManager.GPS_PROVIDER)){
provider=LocationManager.GPS_PROVIDER;
}else{
//当前没有可用的位置提供器
Toast.makeText(this, "No location provider to use", Toast.LENGTH_SHORT).show();
return;
}
//获取当前位置
Location location=locationManager.getLastKnownLocation(provider);
if(location!=null){
//显示当前设备的位置信息
showLocation(location);
}
//位置信息的更新
//第一个参数位置提供器的类型,第二个参数时间间隔,第三个参数距离间隔,第四个参数监听器
locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);

}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(locationManager!=null){
//程序关闭时将监听器移除
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) {
// 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

}

};
private void showLocation(final Location location){
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(location.getLatitude()).append(",");
url.append(location.getLongitude());
url.append("&sensor=false");
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(url.toString());//创建Get请求
//在请求消息头中指定语言,保证服务器会返回中文数据
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);
//获取results节点下的信息
JSONArray resultArray=jsonObject.getJSONArray("results");
if(resultArray.length()>0){
JSONObject subObject=resultArray.getJSONObject(0);
//取出格式化的位置信息
String address=subObject.getString("formatted_address");
Message message=new Message();
message.what=SHOW_LOCATION;
//将结果放入message中
message.obj=address;
handler.sendMessage(message);
}

}


}catch(Exception e){
e.printStackTrace();
}
}

}).start();;


}

}
我们来运行下程序吧,结果如下图所示
 

 

  
    
      
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值