(十四)Android Location的使用!!
最后更新于:2022-04-01 19:46:04
大家好,今天说说**Location**, **Location**在**Android**开发中还是经常用到的,比如 通过经纬度获取天气,根据**Location**获取所在地区详细**Address**(比如**Google Map**开发).等。而在**Android **中通过**LocationManager**来获取**Location**.通常获取**Location**有**GPS**获取,**WIFI**获取。
我今天做一个简单的小**Demo**,来教大家如何获取**Location**,从而获取经纬度。下一节将教大家通过**Location**来获取**Address**.
首先第一步:
创建一个**Android**工程命名为**LocationDemo**.
第二步:修改**main.xml**代码如下:
~~~
~~~
第三步:修改**LocationDemo.java**,代码如下:
~~~
package com.android.tutor;import android.app.Activity;import android.content.Context;import android.location.Location;import android.location.LocationManager;import android.os.Bundle;import android.widget.TextView;public class LocationDemo extends Activity { private TextView longitude; private TextView latitude; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); longitude = (TextView)findViewById(R.id.longitude); latitude = (TextView)findViewById(R.id.latitude); Location mLocation = getLocation(this); longitude.setText("Longitude: " + mLocation.getLongitude()); latitude.setText("Latitude: " + mLocation.getLatitude()); } //Get the Location by GPS or WIFI public Location getLocation(Context context) { LocationManager locMan = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); Location location = locMan .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { location = locMan .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } return location; }}
~~~
第四步:增加权限,修改**AndroidManifest.xml**代码如下(第16行为所增行):
~~~
~~~
第五步:运行**LocationDemo**工程,所得效果如下(真机深圳测试):
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-10_57aae5991fea6.gif)
';